Created
July 24, 2015 06:16
-
-
Save nmandery/d872522dff7635024dfe to your computer and use it in GitHub Desktop.
usage of golang sync.WaitGroup
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" | |
"runtime" | |
) | |
func worker(id int, c chan int, wg *sync.WaitGroup) { | |
wg.Add(1) | |
defer wg.Done() | |
for v := range c { | |
fmt.Printf("id %v: %v\n", id, v) | |
} | |
} | |
func main() { | |
c := make(chan int) | |
var wg sync.WaitGroup | |
for wid:=0; wid<runtime.NumCPU()*2; wid++ { | |
go worker(wid, c, &wg) | |
} | |
for i:=0; i<15; i++ { | |
c <- i | |
} | |
close(c) | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment