Concurrency
suggest changeGo uses goroutines for concurrency. Goroutines are lightweight functions whose execution is scheduled by the Go runtime.
Goroutines may execute concurrently or in parallel, and they share memory.
Concurrent access to shared memory must be synchronized when at least one access is a write. A mutex is one way to provide that synchronization.
Go also provides channels for communicating and synchronizing between goroutines.
Here’s an example of a worker pool of goroutines coordinated with channels:
var wg sync.WaitGroup
func squareWorker(chIn <-chan int, chOut chan<- int) {
fmt.Printf("squareWorker started\n")
for i := range chIn {
square := i * i
chOut <- square
}
fmt.Printf("squareWorker finished\n")
wg.Done()
}
func main() {
chIn := make(chan int)
chOut := make(chan int)
for i := 0; i < 2; i++ {
wg.Add(1)
go squareWorker(chIn, chOut)
}
go func() {
chIn <- 2
chIn <- 4
close(chIn)
}()
go func() {
wg.Wait()
close(chOut)
}()
for square := range chOut {
fmt.Printf("Got square: %d\n", square)
}
}
squareWorker started
Got square: 4
Got square: 16
squareWorker finished
squareWorker started
squareWorker finished
There’s a lot to unpack here.
We launch two workers with go squareWorker(chIn, chOut).
Each squareWorker runs independently and concurrently with the other goroutines.
We send work items through chIn with the <- operator.
The channel operations and sync.WaitGroup methods used here are safe for
concurrent use. This does not make unrelated shared variables safe.
The workers receive values from chIn using range.
We don’t know which worker will pick any given value.
A worker’s for loop terminates when chIn is closed with close(chIn), and then the worker goroutine returns.
To pass results of worker goroutines back to the caller we use another channel.
These channels are unbuffered: their capacity is zero, and each send waits for a corresponding receive. Sending the inputs from another goroutine prevents the main goroutine from blocking before it begins receiving results.
To stop the workers, the sending goroutine closes chIn after the final value.
We then wait for results created by workers by iterating on chOut.
There’s one more complication. Unless we close chOut, the for square := range chOut loop waits forever.
To stop the loop, something must close(chOut). When?
Not inside squareWorker: there are several workers, and closing an already closed channel panics.
sync.WaitGroup is a thread-safe counter that can be incremented / decremented and allows for waiting until the counter reaches 0.
Before launching each worker, we increment the wg counter.
Just before returning, the worker decrements that counter.
We then wg.Wait() for the counter to reach 0, which indicates that all workers have finished and it’s now safe to close the output channel.
It has to happen in its own goroutine to avoid blocking.
Why go to all this trouble to calculate a simple value?
This is a small example. In a real program, each worker goroutine would perform a longer task, such as downloading a file or resizing a large image.
Limiting concurrency with a semaphore