Go by Example

Channel Synchronization

Use channels as done signals to wait for goroutines to finish before continuing.

A channel passes values between goroutines, functions started with go that can run while their caller continues. It can also tell them that an event has happened. chan struct{} carries no data; closing it sends the same stop signal to every goroutine waiting to receive from it.

Each worker waits on the same channel. Closing it lets every worker continue, and a wait group, a counter for tasks, lets main wait until they finish.

package main
 
import (
    "fmt"
    "sync"
)
 
func main() {
    done := make(chan struct{})
    var wg sync.WaitGroup
    for i := 0; i < 3; i++ {
        wg.Add(1)
        go func(id int) {
            defer wg.Done()
            <-done
            fmt.Println("worker stopped:", id)
        }(i)
    }
    close(done)
    wg.Wait()
}

In production

A closed done channel is useful when several functions need the same stop signal. For longer tasks, context.Context is a value passed between functions to carry a stop signal or a deadline, the time by which work should end.

Enjoyed this? Get more software craft delivered to your inbox.