Go•Concurrency
Go Goroutines, Channels, and sync.WaitGroup Concurrency
Learn CSP concurrency in Go: launch thousands of concurrent goroutines and communicate safely via channels.
Syntax
go worker()
ch <- data // send
val := <-ch // receive
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| go | Keyword | Launches a function concurrently on a lightweight green thread. |
| chan T | Type | Typed conduit for sending and receiving values between goroutines. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import (
"fmt"
"sync"
)
func worker(id int, ch chan<- string, wg *sync.WaitGroup) {
defer wg.Done()
ch <- fmt.Sprintf("Worker #%d completed task", id)
}
func main() {
fmt.Println("--- Dispatching Goroutines ---")
var wg sync.WaitGroup
resultChan := make(chan string, 3)
for i := 1; i <= 3; i++ {
wg.Add(1)
go worker(i, resultChan, &wg)
}
wg.Wait()
close(resultChan)
for msg := range resultChan {
fmt.Println("->", msg)
}
fmt.Println("All concurrent workers finished!")
}Expected Output:
--- Dispatching Goroutines --- -> Worker #1 completed task -> Worker #2 completed task -> Worker #3 completed task All concurrent workers finished!
How It Works: Step-by-Step
- Lines 8-11: worker function sends completion message to channel and calls wg.Done().
- Lines 18-22: wg.Add(1) and go worker launches 3 concurrent tasks.
- Lines 24-28: wg.Wait() pauses main until all tasks finish; channel is closed and drained.
Key Concepts
- Goroutines are extremely lightweight (initial stack only ~2KB).
- Channels provide safe synchronization: "Do not communicate by sharing memory; instead, share memory by communicating."
- sync.WaitGroup coordinates execution completion across goroutines.
Common Mistake: Sending to or closing a closed channel
Sending to a closed channel causes an immediate runtime panic.
❌ Incorrect
close(ch); ch <- "val" // Panic: send on closed channel
✅ Correct
// Only close channel once sender is completely done
Related Go Tutorials & Compiler
Go Error Handling: if err != nil, fmt.Errorf, and errors.Is
Master idiomatic Go error handling with explicit error checking and error wrapping (%w).
Go Multiple Return Values and Error Handling Signatures
Master Go signature multiple return values, named returns, and the idiomatic (result, error) convention without exceptions.
Go Methods and Receiver Functions: OOP Without Classes
Implement OOP methods in Go using value and pointer receivers on structs.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.