Concurrency in Go – Goroutines and Sync.WaitGroup Tutorial
What is a Goroutine?
A goroutine is a lightweight thread managed by the Go runtime, letting functions run concurrently with very low overhead.
func sayHello() {
fmt.Println("Hello from goroutine")
}
go sayHello() // runs concurrently
Waiting for Goroutines with sync.WaitGroup
Since the main function doesn't wait for goroutines by default, sync.WaitGroup is used to block until a group of goroutines finishes.
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Println("Worker", id, "done")
}(i)
}
wg.Wait() // blocks until all goroutines call Done()
Why Goroutines Matter
Goroutines make it easy to write highly concurrent programs — handling thousands of simultaneous tasks with far less memory overhead than traditional OS threads.
PreviousError Handling in Go – Custom Errors, Panic, and Recover Guide
Next Channels in Go – Buffered, Unbuffered, and Select Statement
Ready to master real-world Go skills?
Learn Go hands-on with mentor-led, live sessions.
.png)