Skip to content

Instantly share code, notes, and snippets.

@kylelemons
Created August 23, 2011 00:07
Show Gist options
  • Save kylelemons/1163978 to your computer and use it in GitHub Desktop.
Save kylelemons/1163978 to your computer and use it in GitHub Desktop.
Demonstrate a many-producer-to-one-consumer approach
package main
import (
"flag"
"fmt"
"sync"
)
var (
bufSize = flag.Int("buffer", 10, "Buffer size of producer-to-consumer channel")
producers = flag.Int("producers", 10, "Number of producer goroutines")
prodCount = flag.Int("produce-count", 5, "Number of values for each producer to produce")
consCount = flag.Int("consume-count", 30, "Number of values for consumer to consume before signaling the producers to stop")
)
func Produce(wg *sync.WaitGroup, out, stop chan int, id, count int) {
defer wg.Done()
for i := 0; i < count; i++ {
select {
case _, ok := <-stop:
if !ok {
return
}
case out <- id:
}
}
}
func Consume(wg *sync.WaitGroup, in, stop chan int, count int) {
for val := range in {
fmt.Println(val)
if count--; count == 0 {
close(stop)
}
}
}
func main() {
flag.Parse()
wg := new(sync.WaitGroup)
PtoC := make(chan int, *bufSize)
stop := make(chan int)
for i := 0; i < *producers; i++ {
wg.Add(1)
go Produce(wg, PtoC, stop, i, *prodCount)
}
go func() {
wg.Wait()
close(PtoC)
}()
Consume(wg, PtoC, stop, *consCount)
}
$ ./pc | sort -n | uniq -c
5 0
5 1
4 2
4 3
4 4
4 5
4 6
4 7
4 8
3 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment