wasm_spawn_struct.mx raw

   1  // A struct with a []byte crosses a spawn boundary in both directions, and the
   2  // parent joins on the domain's breaker. Runs on every target: natively the
   3  // values travel the mmap ring, on wasm the SAB ring behind the Worker boundary
   4  // (the breaker handle is created by the parent and threaded into the child's
   5  // entry, so `<-done` returns when the child exits).
   6  package main
   7  
   8  type Msg struct {
   9  	N    int32
  10  	Body []byte
  11  }
  12  
  13  func worker(in chan Msg, out chan int32) (closed chan struct{}) {
  14  	select {
  15  	case <-closed:
  16  		return closed
  17  	default:
  18  	}
  19  	for i := 0; i < 2; i++ {
  20  		select {
  21  		case <-closed:
  22  			return closed
  23  		case m := <-in:
  24  			out <- m.N + int32(len(m.Body))
  25  		}
  26  	}
  27  	return closed
  28  }
  29  
  30  func main() {
  31  	select {
  32  	case <-shutdown:
  33  		return
  34  	default:
  35  	}
  36  	in := chan Msg{:2}
  37  	out := chan int32{:2}
  38  	done := spawn(worker, in, out)
  39  	in <- Msg{N: 7, Body: []byte("hello")}
  40  	in <- Msg{N: 9, Body: []byte("world")}
  41  	a := <-out
  42  	b := <-out
  43  	<-done
  44  	if a != 12 || b != 14 {
  45  		panic("spawn struct values wrong")
  46  	}
  47  	println("spawn struct ok", a, b)
  48  }
  49