Skip to content

Instantly share code, notes, and snippets.

@aryszka
Last active May 18, 2017 16:31
Show Gist options
  • Save aryszka/e095a30b94b92a45f1f4b4ba29f18d2e to your computer and use it in GitHub Desktop.
Save aryszka/e095a30b94b92a45f1f4b4ba29f18d2e to your computer and use it in GitHub Desktop.
Go queue with a buffered channel
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func produce(q chan<- int, n int) {
var a int
for a < n {
q <- a
a++
}
close(q)
}
func consume(q <-chan int, wg *sync.WaitGroup) {
for a := range q {
time.Sleep(time.Millisecond * time.Duration(rand.Intn(1000)))
fmt.Println(a)
}
wg.Done()
}
func main() {
const (
numberOfConsumers = 9
numberItems = 100
queueCapacity = numberOfConsumers * 3
)
q := make(chan int, queueCapacity)
var wg sync.WaitGroup
go produce(q, numberItems)
for i := 0; i < numberOfConsumers; i++ {
wg.Add(1)
go consume(q, &wg)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment