Skip to content

Instantly share code, notes, and snippets.

@AxelRHD
Created August 19, 2019 13:11
Show Gist options
  • Save AxelRHD/0b5e76791bc2a87c8ef841145a2cc173 to your computer and use it in GitHub Desktop.
Save AxelRHD/0b5e76791bc2a87c8ef841145a2cc173 to your computer and use it in GitHub Desktop.
Shutdown multiple goroutines over channel
package main
import (
"log"
"sync"
"time"
)
func main() {
var wgDone sync.WaitGroup
shutdownChan := make(chan bool, 1)
for i := 1; i <= 2; i++ {
wgDone.Add(1)
go worker(i, shutdownChan, &wgDone)
}
time.Sleep(time.Second * 5)
shutdownChan <- false
time.Sleep(time.Second * 5)
log.Println("Sending shutdown signal . . .")
close(shutdownChan)
wgDone.Wait()
log.Println("Closing.")
}
func worker(id int, sc chan bool, wg *sync.WaitGroup) {
defer wg.Done()
var cnt int
for {
cnt++
log.Printf("Worker #%02d, loop no %d.\n", id, cnt)
select {
case _, more := <-sc:
if !more {
log.Printf("Worker #%02d got shutdown signal.\n", id)
return
}
log.Printf("Worker #%02d received crap on shutdown channel!\n", id)
default:
}
time.Sleep(time.Second * time.Duration(id+1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment