Repository Description:
This repository is a comprehensive collection of runnable, well-documented examples covering all major concurrency primitives and patterns in Go. It is designed for learners, educators, and developers who want to understand, teach, or demonstrate Go's approach to concurrent programming through clear, minimal, and practical code samples.
This repository contains practical, self-contained examples of Go concurrency primitives and patterns. Each folder demonstrates a specific concept with runnable code and explanations. The goal is to help you understand how to use goroutines, channels, mutexes, and other synchronization tools in real-world scenarios, as well as to illustrate common pitfalls such as race conditions, deadlocks, and goroutine leaks.
- 1. routines/ — Basic goroutine usage
- 2. race-condition/ — Race condition and its fix
- 3. deadlock/ — Deadlock scenario
- 4. livelock/ — Livelock scenario
- 5. starvation/ — Starvation scenario
- 6. wait-group/ — Using and not using sync.WaitGroup
- 7. mutex/ — Mutex, RWMutex, and what happens without them
- 8. cond/ — sync.Cond for goroutine coordination
- 9. once/ — sync.Once for one-time initialization
- 10. channels/ — Channels, buffered channels, select statement
- 11. routine-leaks/ — Goroutine leaks and how to fix them
Navigate to any example directory and run the main file:
go run main.goor for subfolders:
go run with-wait-group/main.go
go run without-mutex/main.go
go run rw-mutex/main.goShows how to launch multiple goroutines and synchronize with time.Sleep.
Demonstrates a race condition when incrementing a shared variable from multiple goroutines, and how to fix it with a mutex and WaitGroup.
Shows a classic deadlock with two mutexes and two goroutines locking in opposite order.
Demonstrates livelock, where goroutines are active but unable to make progress due to repeated retries.
Shows how a greedy goroutine can starve a polite one by monopolizing a lock.
Compares reliable goroutine synchronization with WaitGroup vs. unreliable time.Sleep.
Shows safe and unsafe concurrent access using Mutex and RWMutex, and the problems without them.
Demonstrates goroutine coordination using sync.Cond for signaling and waiting on conditions.
Shows how to use sync.Once to ensure a function is executed only once, even with multiple goroutines.
Demonstrates basic channels, buffered channels (including overflow and multiple senders), and the select statement for handling multiple channels.
Shows how goroutine leaks can occur and how to fix them by properly closing channels and signaling completion.
- Go 1.x or later