Last active
July 29, 2019 15:13
-
-
Save feliperyan/a4d86e7e795fa01dfef0ff55f5ffeeef to your computer and use it in GitHub Desktop.
Example of telling multiple go routines to stop and waiting for them to all stop.
This file contains hidden or 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 ( | |
"fmt" | |
"time" | |
) | |
func doSomework(imDone chan bool, stopMe chan bool, breakTime int, name string) { | |
outer: | |
for { | |
select { | |
case <-stopMe: | |
break outer | |
default: | |
fmt.Printf("Drone-%s is working\n", name) | |
time.Sleep(time.Duration(breakTime) * time.Second) | |
} | |
} | |
imDone <- true | |
return | |
} | |
func main() { | |
stopWorker := make(chan bool) | |
workersDone := make(chan bool) | |
for i := 0; i < 3; i++ { | |
go doSomework(workersDone, stopWorker, i+1, fmt.Sprintf("%d",i)) | |
} | |
go func(breakEmUp chan bool) { | |
time.Sleep(10 * time.Second) | |
fmt.Println("stopping them") | |
breakEmUp <- true | |
breakEmUp <- true | |
breakEmUp <- true | |
return | |
}(stopWorker) | |
for j := 0; j < 3; j++ { | |
<- workersDone | |
} | |
fmt.Println("All stopped.") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment