Go Concurrency

Goroutines, Channels, WaitGroups, and Mutexes

Go
Concurrency
Programming
A comprehensive guide to Go’s concurrency primitives with practical examples
Author

Shane Oh

Published

September 4, 2024

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)
}
Important

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)
}
Note

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
    }
}

Mutexes: Protecting Shared State

While channels are preferred for communication, sometimes you need to protect shared state directly. Mutexes (mutual exclusions) provide synchronized access to shared resources.

package main

import (
    "fmt"
    "sync"
)

type Counter struct {
    mu    sync.Mutex
    value int
}

func (c *Counter) Increment() {
    c.mu.Lock()         // Acquire lock
    defer c.mu.Unlock() // Release lock when function returns
    c.value++
}

func (c *Counter) Value() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.value
}

func main() {
    counter := &Counter{}
    var wg sync.WaitGroup

    // Launch 100 goroutines, each incrementing the counter 100 times
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            for j := 0; j < 100; j++ {
                counter.Increment()
            }
        }()
    }

    wg.Wait()
    fmt.Printf("Final counter value: %d\n", counter.Value()) // Should be 10000
}

RWMutex: Read-Write Locks

When you have many readers and few writers, sync.RWMutex can provide better performance:

package main

import (
    "fmt"
    "sync"
    "time"
)

type SafeMap struct {
    mu   sync.RWMutex
    data map[string]int
}

func NewSafeMap() *SafeMap {
    return &SafeMap{
        data: make(map[string]int),
    }
}

func (sm *SafeMap) Set(key string, value int) {
    sm.mu.Lock()         // Write lock
    defer sm.mu.Unlock()
    sm.data[key] = value
}

func (sm *SafeMap) Get(key string) (int, bool) {
    sm.mu.RLock()         // Read lock
    defer sm.mu.RUnlock()
    val, ok := sm.data[key]
    return val, ok
}

func main() {
    sm := NewSafeMap()
    var wg sync.WaitGroup

    // Writers
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            key := fmt.Sprintf("key%d", i)
            sm.Set(key, i*10)
        }(i)
    }

    // Readers
    for i := 0; i < 20; i++ {
        wg.Add(1)
        go func(i int) {
            defer wg.Done()
            time.Sleep(10 * time.Millisecond) // Give writers time
            key := fmt.Sprintf("key%d", i%5)
            if val, ok := sm.Get(key); ok {
                fmt.Printf("Read %s: %d\n", key, val)
            }
        }(i)
    }

    wg.Wait()
}

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 receiver

Context 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.”