...

/

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 command-line. This is captured in the flag ngoroutine (line 7) when the flags are parsed (line 12). Then, at line 14, we define two integer channels left and right, initializing them. In a for-loop (starting at line 15) with the given number of requests as maxim iteration, we first advance the channels from right to left at line 16. Then, we call the function f, with both channels as a goroutine at line 17. The function f() defined at line 9, takes a value from right, increments it, and puts it on left. Line 19 starts the chaining by putting 0 in the right channel. Line 20 ...