Created
August 19, 2019 13:11
-
-
Save AxelRHD/0b5e76791bc2a87c8ef841145a2cc173 to your computer and use it in GitHub Desktop.
Shutdown multiple goroutines over channel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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