Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- //2020 Aion Algos#9218 http://discord.futuregadgetlab.net
- import (
- "fmt"
- "time"
- "sync"
- )
- func main() {
- fmt.Println("Multi-Producer-Consumer example starting.")
- quantity_per_producer := 100
- producers := 5
- consumers := 20
- buffer := 1
- queue := make(chan int, buffer)
- var pwg sync.WaitGroup
- pwg.Add(producers)
- for i := 0; i < producers; i++ {
- go producer(i, &pwg, queue, quantity_per_producer)
- }
- var cwg sync.WaitGroup
- cwg.Add(consumers)
- for i := 0; i < consumers; i++ {
- go consumer(i, &cwg, queue)
- }
- pwg.Wait()
- close(queue)
- cwg.Wait()
- fmt.Println("Multi-Producer-Consumer example complete.")
- }
- func consumer(id int, wg *sync.WaitGroup, queue <-chan int) {
- fmt.Println("Consumer", id, "started.")
- defer wg.Done()
- for q := range queue {
- fmt.Println("Consumer", id, "recieved:", q)
- time.Sleep(time.Millisecond * 200)
- }
- fmt.Println("Consumer", id, "done.")
- }
- func producer(id int, wg *sync.WaitGroup, queue chan<- int, quantity int) {
- defer wg.Done()
- fmt.Println("Producer", id, "started.")
- for i := 0; i < quantity; i++ {
- queue<- i
- fmt.Println("Producer", id, "produced:", i)
- }
- fmt.Println("Producer", id, "done.")
- }
Add Comment
Please, Sign In to add comment