Last active
August 29, 2015 14:19
-
-
Save miku/a3d26ebd97c5f569f7c4 to your computer and use it in GitHub Desktop.
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
// http://stackoverflow.com/questions/29719780/concurrent-send-receive-go-channel/29719960#29719960 | |
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
// emit emits value count number of times | |
func emit(value string, count int, out chan string, wg *sync.WaitGroup) { | |
defer wg.Done() | |
for i := 0; i < count; i++ { | |
out <- value | |
} | |
} | |
// sink acts as fan in, value are received on out chan | |
func sink(out chan string, done chan bool) { | |
for value := range out { | |
fmt.Println(value) | |
} | |
done <- true | |
} | |
func main() { | |
numWorkers := 4 | |
var wg sync.WaitGroup | |
out := make(chan string) | |
done := make(chan bool) | |
for i := 0; i < numWorkers; i++ { | |
wg.Add(1) | |
go emit(fmt.Sprintf("Value-%d", i), 10, out, &wg) | |
} | |
go sink(out, done) | |
wg.Wait() | |
close(out) | |
<-done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment