Skip to content

Instantly share code, notes, and snippets.

@mssola
Last active December 18, 2015 20:29
Show Gist options
  • Save mssola/5840436 to your computer and use it in GitHub Desktop.
Save mssola/5840436 to your computer and use it in GitHub Desktop.
A simple solution to the classic problem of the "producer-consumer" in Go.
package main
import (
"fmt"
"math/rand"
)
const N_WORKERS = 10
func producer(c chan int) {
c <- rand.Int()
}
func consumer(c chan int, done chan bool) {
for {
num := <-c
fmt.Printf("Producer produced: %v\n", num)
done <- true
}
}
func main() {
c := make(chan int)
done := make(chan bool)
for i := 0; i < N_WORKERS; i++ {
go producer(c)
}
go consumer(c, done)
for i := 0; i < N_WORKERS; i++ {
<-done
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment