GoGo
AdvancedLesson 13 of 15

Mutex, Worker Pools & Context – Go

Protect shared data, distribute work and cancel it.

When several goroutines modify the same data, you need protection. A sync.Mutex allows only one goroutine at a time into the critical section. For simple counters, sync/atomic is faster.

package main

import (
	"fmt"
	"sync"
)

func main() {
	var mu sync.Mutex
	var wg sync.WaitGroup
	zaehler := 0

	for range 1000 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			mu.Lock()
			zaehler++
			mu.Unlock()
		}()
	}
	wg.Wait()
	fmt.Println(zaehler) // 1000
}

The worker pool pattern: a fixed number of goroutines take tasks from a channel and write results into a second one. This is how you limit parallelism.

package main

import "fmt"

func worker(jobs <-chan int, results chan<- int) {
	for j := range jobs {
		results <- j * 2
	}
}

func main() {
	jobs := make(chan int, 5)
	results := make(chan int, 5)

	for w := 0; w < 3; w++ {
		go worker(jobs, results)
	}
	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs)

	summe := 0
	for i := 0; i < 5; i++ {
		summe += <-results
	}
	fmt.Println(summe) // 30
}

The context package carries cancellation signals and deadlines through all layers of an application. By convention, the first parameter of blocking functions is ctx context.Context.

package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()

	select {
	case <-time.After(time.Second):
		fmt.Println("done")
	case <-ctx.Done():
		fmt.Println("cancelled:", ctx.Err()) // cancelled: context deadline exceeded
	}
}
WarningLock without Unlock blocks forever – use defer mu.Unlock() when the section is more than a few lines long. If you forget cancel(), the context leaks resources. Never copy a mutex after first use (e.g. a struct copy containing a mutex field).