A simple Go project demonstrating concurrent message listeners with graceful shutdown.
This project spawns multiple goroutines (βlistenersβ) that poll a shared message at different intervals using time.Ticker.
Each listener reads the message safely via mutex protection and can be stopped gracefully using channels and sync.WaitGroup.
cd listeners
go run .
go build -o listeners main.go
./listeners
Message data from Pro plan listener: initial message
Message data from Pro plan listener: initial message
Message data from Base plan listener: initial message
Pro plan listener stopped!
Base plan listener stopped!
| File | Description |
|---|---|
| main.go | Creates message, starts two listeners (1s and 5s intervals), runs for 6 seconds, then stops them gracefully. |
| listener.go | Defines the Listener struct with Start() and Stop() methods for managing goroutines. |
| message.go | Defines the thread-safe Message struct with mutex-protected read access. |
- Goroutine Management β Uses
sync.WaitGroupto track and wait for all listener goroutines to complete. - Graceful Shutdown β Each listener stops cleanly via a
Donechannel signal. - Thread Safety β Shared
Messagereads are protected bysync.Mutex. - Idempotent Stop β Uses
sync.Onceto safely callStop()multiple times without panics.
GitHub: mr-naveenseven