Go - Channel Chaining
Updated at 2013-12-03 23:21
Goroutines and channels as very lightweight and having thousands of goroutines and channels active shouldn't cause any issues.
package main
func assert(condition bool) {
if !condition {
panic("assert failed")
}
}
func increment(left, right chan int) {
left <- 1 + <-right
}
func main() {
const N = 100000
leftmost := make(chan int)
right := leftmost
left := leftmost
// "queue" a lot of increment operations in goroutine threads
for i := 0; i < N; i++ {
right = make(chan int)
go increment(left, right)
left = right
}
// set it going by providing a single value to the one on top of the stack
// could also simply do `right <- 0`, but that would be a blocking operation
go func(c chan int) { c <- 0 }(right)
// the following blocks until the leftmost channel receives a value
assert(<-leftmost == 100000)
}