Go⚡Concurrencyintermediate
Goroutines
Go · Concurrency · Run with go run
Explanation
A goroutine is a lightweight, cooperatively-scheduled function execution managed by the Go runtime. Starting one costs roughly 2–8 KB of stack (vs. ~1 MB for an OS thread) and the runtime multiplexes thousands of goroutines onto a small pool of OS threads. `go f()` starts `f` concurrently — no callbacks, no futures, just a keyword.
Real-World Scenario
A web server handles each HTTP request in its own goroutine. The Go HTTP server does this automatically — `http.ListenAndServe` spawns a goroutine per connection. At peak load you might have 10,000 concurrent goroutines; the runtime schedules them efficiently without 10,000 OS threads.
Quick Snippet
snippet.go
package main
import (
"fmt"
"time"
)
func worker(id int) {
fmt.Printf("Worker %d starting\n", id)
time.Sleep(100 * time.Millisecond) // simulate work
fmt.Printf("Worker %d done\n", id)
}
func main() {
for i := 1; i <= 5; i++ {
go worker(i) // launch concurrently
}
time.Sleep(500 * time.Millisecond) // wait for workers (use sync.WaitGroup in real code)
}Full Example
goroutines.go
// Compile: go run goroutines.go
// Output (order varies):
// Worker 1 starting
// Worker 2 starting
// ...
// Worker 5 done
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(100 * time.Millisecond)
fmt.Printf("Worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println("all workers done")
}
Run command
go run goroutines.go