Go by Example

Stateful Goroutines

Confine mutable state to a single goroutine and expose it through channels to avoid data races by design.

A goroutine is a function call started with go that can run while its caller continues. A stateful goroutine keeps data that can change and handles every request to read or update it. Since that goroutine is the only one that accesses the data, callers do not need a mutex, a lock for shared data.

The worker is the only code that uses the map. Callers send it a request and wait for a reply. A wait group, a counter used to wait for tasks, confirms that the worker exits after the request channel closes.

package main
 
import (
    "fmt"
    "sync"
)
 
type request struct {
    key   string
    value int
    reply chan int
}
 
func main() {
    requests := make(chan request)
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        values := make(map[string]int)
        for req := range requests {
            values[req.key] = req.value
            req.reply <- values[req.key]
        }
    }()
    req := request{"jobs", 4, make(chan int)}
    requests <- req
    fmt.Println(<-req.reply)
    close(requests)
    wg.Wait()
}

In production

Use this pattern when requests must be handled in a particular order. It adds messages between goroutines and may limit how quickly work finishes, so a mutex is often simpler for basic shared data. Keep all access to the data inside the worker and define how it stops.

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