...

/

Chaining and Parallelizing Computation

Chaining and Parallelizing Computation

This lesson explains how to chain goroutines and parallelize computation over multiple machines.

Chaining goroutines

The following demo-program demonstrates how easy it is to start a massive number of goroutines.

Press + to interact
package main
import (
"flag"
"fmt"
)
var ngoroutine = flag.Int("n", 100000, "how many goroutines")
func f(left, right chan int) { left <- 1+<-right }
func main() {
flag.Parse()
leftmost := make(chan int)
var left, right chan int = nil, leftmost
for i := 0; i < *ngoroutine; i++ {
left, right = right, make(chan int)
go f(left, right)
}
right <- 0 // start the chaining
x := <-leftmost // wait for completion
fmt.Println(x) // 100000, approx. 1.5 s
}

In this little program, you can indicate how many goroutines you want at the ...