Created
November 19, 2017 08:22
-
-
Save jackypanster/7bcdc9331c6d63f9a15a4a4753f53fa7 to your computer and use it in GitHub Desktop.
how to sync goroutines
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 ( | |
"fmt" | |
"sync" | |
) | |
func main() { | |
var wg sync.WaitGroup | |
done := make(chan struct{}) | |
wq := make(chan interface{}) | |
workerCount := 2 | |
for i := 0; i < workerCount; i++ { | |
wg.Add(1) | |
go doit(i,wq,done,&wg) | |
} | |
for i := 0; i < workerCount; i++ { | |
wq <- i | |
} | |
close(done) | |
wg.Wait() | |
fmt.Println("all done!") | |
} | |
func doit(workerId int, wq <-chan interface{},done <-chan struct{},wg *sync.WaitGroup) { | |
fmt.Printf("[%v] is running\n",workerId) | |
defer wg.Done() | |
for { | |
select { | |
case m := <- wq: | |
fmt.Printf("[%v] m => %v\n",workerId,m) | |
case <- done: | |
fmt.Printf("[%v] is done\n",workerId) | |
return | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment