GoGo

Go: Concurrency – code examples

Contents

Goroutines with WaitGroup

Concurrency#goroutine#waitgroup#parallel#sync
Use case: Complete many independent tasks (downloads, calculations) at the same time.
package main

import (
	"fmt"
	"sync"
)

func main() {
	ergebnisse := make([]int, 5)
	var wg sync.WaitGroup
	for i := range 5 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			ergebnisse[i] = i * i
		}()
	}
	wg.Wait()
	fmt.Println(ergebnisse) // [0 1 4 9 16]
}

Each goroutine writes to its own slice index – so there is no data race. Wait blocks until all have called Done. Requires Go 1.22+ (own loop variable per iteration).

Channel with timeout

Concurrency#select#channel#timeout
Use case: Wait for a response, but not forever (network, background jobs).
package main

import (
	"fmt"
	"time"
)

func main() {
	antwort := make(chan string)
	go func() {
		time.Sleep(200 * time.Millisecond)
		antwort <- "Ergebnis"
	}()

	select {
	case a := <-antwort:
		fmt.Println(a)
	case <-time.After(50 * time.Millisecond):
		fmt.Println("Timeout") // Timeout
	}
}

select takes whichever case is ready first. Here the timeout wins after 50 ms. The goroutine may then be stuck sending – in real code you would use a buffered channel or context.

Counter with mutex

Concurrency#mutex#sync#race
Use case: Protect shared data (counters, caches) from concurrent access.
package main

import (
	"fmt"
	"sync"
)

type SichererZaehler struct {
	mu sync.Mutex
	n  int
}

func (z *SichererZaehler) Inc() {
	z.mu.Lock()
	defer z.mu.Unlock()
	z.n++
}

func main() {
	var z SichererZaehler
	var wg sync.WaitGroup
	for range 100 {
		wg.Add(1)
		go func() { defer wg.Done(); z.Inc() }()
	}
	wg.Wait()
	fmt.Println(z.n) // 100
}

The mutex belongs as a field in the struct it protects; defer Unlock guarantees the release. Never copy a struct containing a mutex – always use it via a pointer.

Cancellation with context

Concurrency#context#timeout#cancel
Use case: Cleanly end running operations on timeout or user cancellation (HTTP handlers, database).
package main

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

func arbeite(ctx context.Context) error {
	select {
	case <-time.After(time.Second):
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()
	fmt.Println(arbeite(ctx)) // context deadline exceeded
}

WithTimeout returns a context that is "done" after the deadline. Blocking functions check ctx.Done() and return ctx.Err(). You pass the context on as the first parameter.

Worker pool

Concurrency#worker#pool#channel#waitgroup
Use case: Process many tasks with limited parallelism (image processing, API calls).
package main

import (
	"fmt"
	"sync"
)

func main() {
	jobs := make(chan int)
	results := make(chan int, 10)
	var wg sync.WaitGroup

	for w := 0; w < 3; w++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := range jobs {
				results <- j * j
			}
		}()
	}
	for j := 1; j <= 5; j++ {
		jobs <- j
	}
	close(jobs)
	wg.Wait()
	close(results)

	summe := 0
	for r := range results {
		summe += r
	}
	fmt.Println(summe) // 55
}

Three workers take jobs from a channel. After close(jobs) they end their loop; only after wg.Wait() is results closed. 1+4+9+16+25 = 55.