api: "YAML JSON TOON Database" version: 1.0.0 format: toon dataset: id: 414 slug: go-concurrency-patterns title: "Go Concurrency Patterns" description: "Goroutines, channels, select, sync primitives, and common concurrency patterns in Go." category: "Programming Languages" category_slug: programming-languages tags: "go,golang,concurrency,goroutines,channels" view_count: 1 created_at: 1781275786 updated_at: 1781275786 data: concepts - name: Goroutines keyword: go description: "Lightweight threads managed by Go runtime; cheap to create (few KB stack)." example: "go func() { fmt.Println(\"running in goroutine\") }()" notes: " thousands of concurrent goroutines possible; multiplexed onto OS threads" - name: Channels keyword: chan description: "Typed conduits for communication between goroutines; synchronous or buffered." example: "ch := make(chan int); go func() { ch <- 42 }(); val := <-ch" notes: "Blocking by default; unbuffered channels synchronize goroutines" - name: "Buffered Channels" keyword: "make(chan T, n)" description: "Channels with capacity; sender blocks only when buffer full." example: "bufCh := make(chan string, 5); bufCh <- \"msg\"; // non-blocking if space" notes: "Useful for queue-like patterns; decouples sender/receiver rates" - name: "Select Statement" keyword: select description: "Wait on multiple channel operations; like switch for channels." example: "select { case msg := <-ch1: fmt.Println(msg) case msg := <-ch2: fmt.Println(msg) case <-time.After(time.Second): fmt.Println(\"timeout\") }" notes: "Random choice if multiple ready; default case non-blocking" - name: WaitGroup keyword: sync.WaitGroup description: "Wait for a collection of goroutines to finish; Add, Done, Wait." example: "var wg sync.WaitGroup; wg.Add(2); go func(){ defer wg.Done(); ... }(); wg.Wait()" notes: "Must call Done exactly once per Add; typically defer wg.Done()" - name: "Mutex (Mutual Exclusion)" keyword: sync.Mutex description: "Protect shared memory; Lock/Unlock ensure exclusive access." example: "var mu sync.Mutex; mu.Lock(); counter++; mu.Unlock()" notes: "Prefer channels over mutexes when possible (communicating vs sharing)" - name: "Worker Pool Pattern" pattern: "Fan-out / Fan-in" description: "Distribute work across multiple workers; collect results." example: "jobs := make(chan Job); results := make(chan Result); for w:=1; w<=3; w++ { go worker(jobs, results) }; for j:=range jobs { jobs <- j }; close(results); for r:=range results { ... }" notes: "Classic pipeline: distribute tasks, process concurrently, collect" - name: "Context Package" keyword: context.Context description: "Carry deadlines, cancellation signals, and request-scoped values across API boundaries." example: "ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second); defer cancel(); select { case <-ctx.Done(): fmt.Println(\"timeout\") }" notes: "Use for cancellation, timeouts, and passing request-scoped data"