Skip to content

Instantly share code, notes, and snippets.

@alxfv
Created April 13, 2019 15:39
Show Gist options
  • Save alxfv/f11141f01d78f2486608e9a16405d409 to your computer and use it in GitHub Desktop.
Save alxfv/f11141f01d78f2486608e9a16405d409 to your computer and use it in GitHub Desktop.
Producer-consumer in Golang
package main
import (
"fmt"
"math/rand"
"time"
)
const (
N = 20
)
func delay() {
time.Sleep(time.Millisecond * time.Duration(rand.Intn(100)))
}
/* Producer accept channel "items" only for sending values */
func producer(items chan<- int) {
defer close(items)
for i := 0; i < N; i++ {
delay()
items <- i
fmt.Println(i, "th item produced")
}
}
/* Consumer accept channel "items" only for receiving values */
func consumer(items <-chan int, done chan<- bool) {
for data := range items {
delay()
fmt.Println("Consumed item #", data)
}
fmt.Println("Finished consumption")
done <- true
}
func main() {
items := make(chan int, 10)
done := make(chan bool)
go producer(items)
go consumer(items, done)
<-done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment