select and sync
| Multiplex with select | |
| Timeouts with time.After | |
| Mutex guards state | |
| sync.Once |
Multiplex with select
select waits on several channels at once and runs the case that becomes ready first. It is the switch statement of concurrent code. When two cases are ready together, one wins at random. The example below races two workers and prints the winner.
package main
import "fmt"
func main() {
a := make(chan string)
b := make(chan string)
go func() { a <- "from a" }()
go func() { b <- "from b" }()
select {
case m := <-a:
fmt.Println(m)
case m := <-b:
fmt.Println(m)
}
}
Either line may print, and both outcomes are correct. A default case would make select non-blocking instead of waiting. Timeouts below use the blocking form on purpose.
Timeouts with time.After
time.After returns a channel that delivers one value after the given duration. Racing work against that channel bounds any wait. The slow path reports a timeout while the worker keeps going in the background. Pair this with cancelable contexts for production code.
package main
import (
"fmt"
"time"
)
func main() {
done := make(chan string)
go func() {
time.Sleep(300 * time.Millisecond)
done <- "result"
}()
select {
case r := <-done:
fmt.Println(r)
case <-time.After(100 * time.Millisecond):
fmt.Println("timed out")
}
}
timed out
The worker needs 300 milliseconds but patience runs out after 100. Note the orphaned worker still sends later with nobody listening. Real services stop such work through a done channel or a context.
Mutex guards state
Channels share data by moving it, but plain variables need a Mutex instead. Lock before touching shared state and Unlock right after. Keep the locked region tiny so routines wait less. The counter below reaches exactly 100 only because of the lock.
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
total := 0
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
total++
mu.Unlock()
}()
}
wg.Wait()
fmt.Println(total)
}
100
Without the lock, increments would interleave and the total would land short. defer Unlock is an option, but explicit Unlock keeps hot paths fast. The race detector, run with the -race flag, proves the fix.
sync.Once
sync.Once runs a function exactly one time, no matter how many routines call it. Lazy singletons, config loads, and connection pools all fit. Every caller blocks until the single run finishes. Later calls pay almost nothing.
package main
import (
"fmt"
"sync"
)
var once sync.Once
var conf string
func load() {
once.Do(func() {
conf = "loaded once"
})
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func() {
defer wg.Done()
load()
}()
}
wg.Wait()
fmt.Println(conf)
}
loaded once
Next: CLI: args, flags, env
Article author: Arthur Isaev