← Zurück zum Kurs: Go from scratch

select, WaitGroup and Mutex

Video folgt in Kürze

With goroutines and channels you can already distribute work, but real programs need three more tools. First, waiting for a group of goroutines to finish without arbitrary pauses: that is the role of sync.WaitGroup. Second, waiting on several channels at once and reacting to the first one that is ready, or stop waiting after some time: select does that. Third, protecting data that several goroutines modify simultaneously, for which sync.Mutex exists. Today you see all three, together with the main bug concurrency causes: the race condition.

sync.WaitGroup

A WaitGroup is a counter. Before launching each goroutine you call wg.Add(1); when the goroutine ends, it calls wg.Done() (almost always with defer, so it runs even on error); and whoever needs to wait calls wg.Wait(), which blocks until the counter reaches zero. There are two typical mistakes: calling Add inside the goroutine, when it might already be too late, and passing the WaitGroup by value to a function, which copies it so the original never finds out; always pass it by pointer. Since Go 1.25 there is wg.Go, but in Go 1.23 the Add and Done pattern is the one you must master.

Race conditions and Mutex

If two goroutines modify the same variable at once, the result is unpredictable: it is a race condition. Even a simple counter++ is not atomic, because it is three steps (read, add, write) that can interleave. A sync.Mutex solves it: Lock() takes the lock and Unlock() releases it; only one goroutine at a time can be between them. The usual way is to put the mutex inside the struct it protects and use defer mu.Unlock() right after Lock. For data read a lot and written little there is sync.RWMutex. You can detect races by running go run -race or go test -race.

go
package main

import (
	"fmt"
	"sync"
)

type SafeCounter struct {
	mu    sync.Mutex
	count map[string]int
}

func (c *SafeCounter) Inc(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.count[key]++
}

func (c *SafeCounter) Value(key string) int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.count[key]
}

func main() {
	c := &SafeCounter{count: make(map[string]int)}
	var wg sync.WaitGroup

	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			c.Inc("hits")
		}()
	}
	wg.Wait() // wait for all 100 goroutines

	fmt.Println(c.Value("hits")) // always 100
}

select

select looks like a switch, but each case is a channel operation. It waits until one is ready and runs that case; if several are ready at once, it picks one at random. With a default case it does not block: if nothing is ready, it runs the default, which is useful for non-waiting attempts. Combined with time.After(d), which returns a channel that receives a value after duration d, timeouts are implemented. This is essential in network programs: never wait on something external without giving it a deadline.

go
package main

import (
	"fmt"
	"time"
)

func slowWork(d time.Duration) <-chan string {
	ch := make(chan string, 1) // buffered: the goroutine never leaks
	go func() {
		time.Sleep(d)
		ch <- "done"
	}()
	return ch
}

func main() {
	select {
	case msg := <-slowWork(10 * time.Millisecond):
		fmt.Println(msg) // done
	case <-time.After(500 * time.Millisecond):
		fmt.Println("timeout")
	}

	select {
	case msg := <-slowWork(2 * time.Second):
		fmt.Println(msg)
	case <-time.After(50 * time.Millisecond):
		fmt.Println("timeout") // this one wins
	}

	ready := make(chan int)
	select {
	case v := <-ready:
		fmt.Println(v)
	default:
		fmt.Println("nothing ready, moving on")
	}
}
  • wg.Add(1) before launching; defer wg.Done() inside; wg.Wait() to wait.
  • Always pass WaitGroup and Mutex by pointer (never copy them).
  • Lock and defer Unlock protect shared data.
  • select waits on several channels; default avoids blocking.
  • Test with go test -race to find races.

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →