select and sync

Contents
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

Related articles
Golang
Go course: zero to hero in 50 lessons
What is Go and where it runs
Install Go and check the version
Your first Go program
Modules with go mod
Variables
Constants
Types
Numbers
Strings
Conditions with if
Switch in Go
Loops with for
Arrays in Go
Slices in Go
Maps in Go
Functions in Go
Errors as values
Pointers in Go
Structs in Go
Methods in Go
Interfaces in Go
Embedding instead of inheritance
Generics in Go
Packages and imports
The go toolchain
Testing with go test
Advanced errors
defer in Go
Strings, bytes and runes
Time in Go
JSON
Files and IO
HTTP servers
HTTP clients
Context
Goroutines
Channels
select and sync
CLI: args, flags, env
Logging
Regular expressions
Sorting
Concurrency patterns
Databases with database/sql
Benchmarks and profiling
Toolchain and CI
Project layout
Capstone: wordfreq CLI
Capstone: JSON API server
Hero roadmap: the whole course on one page
Install Go on Windows 11
Install Go on Ubuntu
Install Go on Rocky Linux
Install Go on macOS
Install Go on FreeBSD
Go in Docker

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: