main.mx raw

   1  // Measures what a spawn costs on this box, which is the input to the pool
   2  // decision: if a spawn is a fork (an OS thread with its own domain and arena
   3  // stack), then one spawn per request is a thread per request, and a fixed pool
   4  // is the only bound that makes sense. Prints microseconds per spawn.
   5  package main
   6  
   7  import (
   8  	"fmt"
   9  	"time"
  10  )
  11  
  12  func worker(ch chan []byte) (closed chan struct{}) {
  13  	done := false
  14  	for !done {
  15  		select {
  16  		case <-closed:
  17  			return closed
  18  		default:
  19  		}
  20  		m := <-ch
  21  		if m == "stop" {
  22  			done = true
  23  		}
  24  	}
  25  	return closed
  26  }
  27  
  28  func main() {
  29  	// Termination: a batch program must still be stoppable, so the entry
  30  	// handles the channel the runtime closes on SIGINT/SIGTERM.
  31  	select {
  32  	case <-shutdown:
  33  		return
  34  	default:
  35  	}
  36  
  37  	const n = 16
  38  	ch := chan []byte{}
  39  	t0 := time.Now()
  40  	for i := 0; i < n; i++ {
  41  		spawn(worker, ch)
  42  	}
  43  	el := time.Since(t0)
  44  	// Plain int64s: a named Duration has no builtin stringer, so %d on it
  45  	// prints "?" instead of the measurement.
  46  	us := int64(el / time.Microsecond)
  47  	per := us / int64(n)
  48  	fmt.Printf("spawns=%d total_us=%d per_spawn_us=%d\n", n, us, per)
  49  	for i := 0; i < n; i++ {
  50  		ch <- []byte("stop")
  51  	}
  52  }
  53