Go Concurrency
Goroutines, Channels, WaitGroups, and Mutexes
Checkout the video by Ben Davis. Great explanation!
I recently started learning Go (Golang) and I find it easy to pick up. There isn’t much magic involved, which gives me a solid, reliable feeling when working with it. Go’s approach to concurrency is one of its standout features, built around the philosophy: “Don’t communicate by sharing memory; share memory by communicating.”
Let’s dive into the concurrency world of Go and explore its key primitives.
Goroutines: Lightweight Threads
Goroutines are Go’s lightweight threads managed by the Go runtime. They’re incredibly cheap to create - you can spawn thousands of them without significant overhead.
package main
import (
"fmt"
"time"
)
func main() {
// Launch a goroutine
go sayHello("World")
// Main goroutine continues
fmt.Println("Main function")
// Give the goroutine time to complete
time.Sleep(1 * time.Second)
}
func sayHello(name string) {
fmt.Printf("Hello %s\n", name)
}The main function doesn’t wait for goroutines to complete by default. If the main function exits, all goroutines are terminated regardless of their state.
Wait Groups: Coordinating Goroutines
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Each goroutine runs and calls Done when finished. We use defer to ensure Done is called even if the function panics.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
names := []string{
"Alice", "Bob", "Chuck", "Dan", "Ed", "Fred", "Greg",
}
var wg sync.WaitGroup
for _, name := range names {
wg.Add(1) // Increment the counter
go func(name string) {
defer wg.Done() // Decrement the counter when done
sayHello(name)
}(name) // Pass name as parameter to avoid closure issues
}
wg.Wait() // Block until counter reaches zero
fmt.Println("All greetings completed!")
}
func sayHello(name string) {
time.Sleep(100 * time.Millisecond) // Simulate work
fmt.Printf("Hello %v\n", name)
}Think of wg as a counter. The counter increments with values passed to Add and decreases by one with each Done call. Wait blocks until the counter reaches zero.
Channels: Communication Between Goroutines
Channels are Go’s way of allowing goroutines to communicate safely. They’re typed conduits that can send and receive values of a specific type.
Basic Channel Operations
package main
import "fmt"
func main() {
ch := make(chan int) // Create an unbuffered channel
go func() {
ch <- 1 // Send values
ch <- 2
ch <- 3
close(ch) // Close the channel when done
}()
// Receive values
fmt.Println(<-ch) // 1
fmt.Println(<-ch) // 2
fmt.Println(<-ch) // 3
fmt.Println(<-ch) // 0 (zero value from closed channel)
}Range Over Channels
A more elegant way to receive from channels is using range:
package main
import "fmt"
func main() {
ch := make(chan int)
go func() {
for i := 1; i <= 5; i++ {
ch <- i
}
close(ch) // Important: close the channel
}()
// Range automatically breaks when channel is closed
for num := range ch {
fmt.Printf("Received: %d\n", num)
}
}Select Statement: Non-blocking Operations
The select statement lets you wait on multiple channel operations:
package main
import (
"fmt"
"time"
)
func main() {
ch1 := make(chan string)
ch2 := make(chan string)
go func() {
time.Sleep(1 * time.Second)
ch1 <- "Channel 1"
}()
go func() {
time.Sleep(2 * time.Second)
ch2 <- "Channel 2"
}()
for i := 0; i < 2; i++ {
select {
case msg1 := <-ch1:
fmt.Println("Received:", msg1)
case msg2 := <-ch2:
fmt.Println("Received:", msg2)
case <-time.After(3 * time.Second):
fmt.Println("Timeout!")
}
}
}Practical Example: Worker Pool
Here’s a more complex example using channels to implement a worker pool pattern:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
jobs := make(chan int, 100)
results := make(chan int, 100)
// Start 3 workers
var wg sync.WaitGroup
for w := 1; w <= 3; w++ {
wg.Add(1)
go worker(w, jobs, results, &wg)
}
// Send jobs
for j := 1; j <= 9; j++ {
jobs <- j
}
close(jobs)
// Wait for workers to finish
go func() {
wg.Wait()
close(results)
}()
// Collect results
for result := range results {
fmt.Printf("Result: %d\n", result)
}
}
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
fmt.Printf("Worker %d processing job %d\n", id, job)
time.Sleep(time.Second) // Simulate work
results <- job * 2
}
}Best Practices and Common Patterns
Channel Direction
You can restrict channels to be send-only or receive-only:
func sender(ch chan<- int) { // Send-only channel
ch <- 42
}
func receiver(ch <-chan int) { // Receive-only channel
value := <-ch
fmt.Println(value)
}Buffered Channels
Buffered channels can hold a limited number of values without blocking:
ch := make(chan int, 3) // Buffer size of 3
ch <- 1 // Doesn't block
ch <- 2 // Doesn't block
ch <- 3 // Doesn't block
ch <- 4 // Would block without a receiverContext for Cancellation
Use context for graceful cancellation:
package main
import (
"context"
"fmt"
"time"
)
func worker(ctx context.Context) {
for {
select {
case <-ctx.Done():
fmt.Println("Worker cancelled")
return
default:
fmt.Println("Working...")
time.Sleep(500 * time.Millisecond)
}
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
go worker(ctx)
time.Sleep(3 * time.Second) // Wait longer than context timeout
}Conclusion
Go’s concurrency model provides powerful, yet simple tools for building concurrent applications:
- Goroutines for lightweight parallel execution
- Channels for safe communication between goroutines
- WaitGroups for synchronizing goroutine completion
- Mutexes for protecting shared state when channels aren’t suitable
The key is choosing the right tool for each situation. Start with channels and goroutines - they solve most concurrency problems elegantly. Use mutexes sparingly, only when you need to protect shared state that doesn’t fit the channel communication model.
Remember: “Don’t communicate by sharing memory; share memory by communicating.”