Goroutine — Explained with Examples
A goroutine is a lightweight thread managed by the Go runtime, multiplexed onto OS threads with efficient stack management.
Goroutines are functions or methods that run concurrently with other goroutines. Unlike OS threads, goroutines start with tiny stacks (a few KB) that grow and shrink as needed, allowing millions of goroutines in a single process. The Go scheduler multiplexes goroutines onto OS threads using M:N scheduling. Goroutines communicate via channels (CSP-style) or shared memory with mutexes.
Think of goroutines like a team of chefs in a busy kitchen. Instead of each chef having their own full kitchen (OS thread), they share a few kitchen stations (OS threads). A chef can pause one dish (goroutine blocks), start another, and seamlessly switch between tasks. The head chef (Go scheduler) assigns chefs to stations efficiently.
The go keyword launches a goroutine. The sync.WaitGroup coordinates completion, and select handles multiple channel operations.
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println("All workers finished")
}Goroutines are the foundation of Go’s concurrency model. They make concurrent programming accessible by combining lightweight syntax, safe channel communication, and built-in race detection.
Coroutine, CSP, Actor Model, Thread, Async/Await
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro