Go
Go was designed at Google (Robert Griesemer, Rob Pike, Ken Thompson) and released in 2009. Its concurrency model comes from Tony Hoare's CSP (Communicating Sequential Processes): lightweight goroutines run independently and exchange values over typed channels. The slogan is "share memory by communicating".
Paradigm: Concurrent and Actor Programming
What Makes Go Special
- Goroutines. Put
gobefore a function call and it runs concurrently. Goroutines cost a few kilobytes, so programs can have hundreds of thousands. - Channels. A
chan intis a typed pipe. Sending blocks until someone receives (for an unbuffered channel), so channels also synchronize. - select. A
selectstatement waits on several channels at once, which is how timeouts, cancellation and multiplexing are written. - Simple language, fast tools. There is one obvious loop (
for), garbage collection, static binaries and very fast compilation. - Tools for the shared-memory case. When sharing is unavoidable,
sync.Mutex,sync.WaitGroupand the race detector (go test -race) are available.
Example: A worker pool
package main
import (
"fmt"
"sync"
)
func main() {
jobs := make(chan int)
results := make(chan int, 5)
var wg sync.WaitGroup
for w := 0; w < 3; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for n := range jobs {
results <- n * n
}
}()
}
for n := 1; n <= 5; n++ {
jobs <- n
}
close(jobs)
wg.Wait()
close(results)
sum := 0
for r := range results {
sum += r
}
fmt.Println(sum)
}
How It Works
- Three goroutines each read numbers from the
jobschannel until it is closed and send the squares toresults. - The main goroutine sends 1 to 5 into
jobs, and whichever worker is free takes the next number. The work is spread without any explicit scheduling. WaitGroupletsmainwait until all workers finish.resultsis buffered so workers never block.- Closing
resultsends the last loop. The program prints55(1 + 4 + 9 + 16 + 25), whatever order the workers run in.
History and Where It Is Used
Go powers cloud infrastructure: Docker, Kubernetes, Terraform, Prometheus and many network services. Its simple concurrency and single-binary deployment make it a favorite for back ends and command-line tools. See the Go roadmap for a complete course.
Learn More
- A Tour of Go
- Go (Wikipedia)
- Back to Concurrent and Actor Programming or the PGP roadmap.