2025-11-18 · Go
Asynchronous Computing in Go (Goroutines)
Go Goroutine
Goroutine
A goroutine is a lightweight thread (user-space thread) managed by Go itself, rather than a thread managed by the operating system (OS thread), with extremely low creation and context-switching costs.
Under the hood, Go uses an M:N scheduling model. This means that M goroutines are assigned to N operating system threads for execution. When a goroutine blocks, the scheduler schedules other work to run.
The go keyword creates a goroutine:
func someFunc(num string) { fmt.Println(num)}
func main() { go someFunc("1") go someFunc("2") go someFunc("3")
// Deliberately wait 2 seconds for other goroutines to finish before the main goroutine exits time.Sleep(time.Second * 2) fmt.Println("Hi")}The numbers may print in a different order each time, demonstrating that goroutines execute code concurrently.
Channel
Do not communicate by sharing memory; instead, share memory by communicating.
Unlike other languages that share memory and use locks to avoid race conditions, Go uses channels to avoid data contention, since values are passed between goroutines by copying.
Think of a channel as a portal: one goroutine sends data through one end, and another goroutine receives it at the other end.
func main() { myChannel := make(chan string)
go func() { myChannel <- "data" }()
// Blocks until the channel is closed or a message is received msg := <-myChannel fmt.Println(msg)}Unbuffered vs Buffered Channel
A channel has a sending end and a receiving end. An unbuffered channel has no buffer space, so a sending goroutine waits until its value is received:
ch := make(chan int)
go func() { fmt.Println("sending...") ch <- 1 // Blocks until the main goroutine receives fmt.Println("sent")}()
fmt.Println("receiving...")value := <-ch // The sender can continue only once this line is reachedfmt.Println("received:", value)With a buffered channel, a send does not necessarily need an immediate matching receive. Instead, sending blocks only when the buffer is full, and receiving blocks when the buffer is empty.
# This means all goroutines in the program are waiting for something that will never happen (for example, no goroutine will ever send to or receive from a channel again), bringing execution to a halt.fatal error: all goroutines are asleep - deadlock!ch := make(chan int, 2)
ch <- 1 // Does not blockch <- 2 // Does not blockch <- 3 // Blocks because the buffer is full
fmt.Println(<-ch) // 1fmt.Println(<-ch) // 2Buffered channels are commonly used in producer-consumer models with mismatched rates, but are not suitable as concurrency control tools (for limiting concurrency, ensuring mutually exclusive access, and so on).
Close
Channels can be closed. For example, two goroutines communicate through a channel, one sending and the other receiving. If the sender stops writing data but the receiver keeps trying to receive, the receiver will block forever. The solution is to close the channel once it is no longer needed.
func main() { dataChan := make(chan int)
go func() { for i := 0; i < 1000; i++ { dataChan <- i } close(dataChan) }()
for n := range dataChan { fmt.Printf("n = %d\n", n) }}defer
Schedules code to run when the current function exits, whether through a normal return, a panic, or an early return, preventing Wait() from blocking forever.
func main() { defer fmt.Println("world")
fmt.Println("hello")}WaitGroup
The fork-join parallel computing model splits a large task into independent smaller tasks, runs them simultaneously, and combines their results.
- Fork: Split into multiple parallel tasks
- Join: Wait for all tasks to finish, then combine the results
A WaitGroup is a tool for implementing the fork-join pattern, used to wait for a group of goroutines to finish.:
wg.Add(n): Specifies how many tasks to wait for (usually the number of goroutines)wg.Done(): Signals completion, equivalent towg.Add(-1)wg.Wait(): The goroutine waits here until all tasks finish before continuing.
func main() { var wg sync.WaitGroup
wg.Add(3) // Wait for three goroutines
for i := 1; i <= 3; i++ { go func(id int) { defer wg.Done()
fmt.Println("Worker", id, "done") }(i) }
wg.Wait() // Wait for all workers to finish fmt.Println("All workers finished")}Select
A control structure for handling multiple channel operations: it executes whichever operation is ready first. It is similar to a switch, but specifically for channel communication. If multiple cases are ready, one is chosen using a uniform pseudorandom selection.
func main() { myChannel := make(chan string) myAnotherChannel := make(chan string)
go func() { myChannel <- "data" }()
go func() { myAnotherChannel <- "data2" }()
// Blocks until a channel in any case is closed or a message can be received // If multiple cases are ready, one is chosen using a uniform pseudorandom selection. select { case msg := <-myChannel: fmt.Println("a", msg) case msg2 := <-myAnotherChannel: fmt.Println("b", msg2) }
}select {case result := <-ch: fmt.Println("Success:", result)case <-time.After(3 * time.Second): fmt.Println("Timed out!")}