Here’s a little program I wrote in Go. In it, I wanted to explore how it might work to create a giant “onion” of threads, passing messages in towards the center, where they would be reflected and sent back out. Why? Just for fun, to solidify my grasp on the syntax, to see what would happen.
Here’s my program:
package main import ( "fmt" "time" ) func make2() (chan int, chan int) { return make(chan int), make(chan int) } func makeAndEcho(ct int, in, out chan int) { var in2, out2 chan int; echo := func () { for !closed(in) { x := <-in out <- x } } pass := func () { for !closed(in) { select { case x := <-in: { in2 <- x } case x := <-out2: { out <- x } } } } if (ct == 0) { go echo() } else { in2, out2 = make2() makeAndEcho(ct-1, in2, out2) go pass() } } func try(depth, n int) { in, out := make2() makeAndEcho(depth, in, out) before := time.Nanoseconds() for i := 0; i < n; i++ { in <- 1 _ = <- out } close(in) after := time.Nanoseconds() transits := int64(n*depth*2) fmt.Printf( "%v round-trips, %v nsec/trip, %v nsec/transit for %v transits\n", n, (after-before)/int64(n), (after-before)/int64(transits), transits); } func main() { try(10, 10000) try(100, 10000) ch := make(chan int, 1) before := time.Nanoseconds() for i := 0; i < 200000; i++ { ch <- i _ = <- ch } after := time.Nanoseconds() fmt.Printf( "no threads: %v nsec/transit for %v transits\n", (after-before)/200000, 200000) } When you run it, you get this:
...