Created
April 13, 2019 15:39
-
-
Save alxfv/f11141f01d78f2486608e9a16405d409 to your computer and use it in GitHub Desktop.
Producer-consumer in Golang
This file contains hidden or 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
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