alaestor

[Go] p2 multi-producer-consumer

Aug 31st, 2020
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.24 KB | None | 0 0
  1. package main
  2. //2020  Aion Algos#9218 http://discord.futuregadgetlab.net
  3. import (
  4.   "fmt"
  5.   "time"
  6.   "sync"
  7. )
  8.  
  9. func main() {
  10.   fmt.Println("Multi-Producer-Consumer example starting.")
  11.   quantity_per_producer := 100
  12.   producers := 5
  13.   consumers := 20
  14.   buffer := 1
  15.  
  16.   queue := make(chan int, buffer)
  17.  
  18.   var pwg sync.WaitGroup
  19.   pwg.Add(producers)
  20.   for i := 0; i < producers; i++ {
  21.     go producer(i, &pwg, queue, quantity_per_producer)
  22.   }
  23.  
  24.   var cwg sync.WaitGroup
  25.   cwg.Add(consumers)
  26.   for i := 0; i < consumers; i++ {
  27.     go consumer(i, &cwg, queue)
  28.   }
  29.  
  30.   pwg.Wait()
  31.   close(queue)
  32.   cwg.Wait()
  33.   fmt.Println("Multi-Producer-Consumer example complete.")
  34. }
  35.  
  36. func consumer(id int, wg *sync.WaitGroup, queue <-chan int) {
  37.   fmt.Println("Consumer", id, "started.")
  38.   defer wg.Done()
  39.   for q := range queue {
  40.     fmt.Println("Consumer", id, "recieved:", q)
  41.     time.Sleep(time.Millisecond * 200)
  42.   }
  43.   fmt.Println("Consumer", id, "done.")
  44. }
  45.  
  46. func producer(id int, wg *sync.WaitGroup, queue chan<- int, quantity int) {
  47.   defer wg.Done()
  48.   fmt.Println("Producer", id, "started.")
  49.   for i := 0; i < quantity; i++ {
  50.     queue<- i
  51.     fmt.Println("Producer", id, "produced:", i)
  52.   }
  53.   fmt.Println("Producer", id, "done.")
  54. }
  55.  
Add Comment
Please, Sign In to add comment