alaestor

[Go] p1 producer-consumer

Aug 31st, 2020
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.05 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("Producer-Consumer example starting.")
  11.   quantity := 30
  12.   consumers := 3
  13.   buffer := 3
  14.  
  15.   queue := make(chan int, buffer)
  16.  
  17.   var wg sync.WaitGroup
  18.   wg.Add(consumers + 1)
  19.   go producer(&wg, queue, quantity)
  20.   for i := 0; i < consumers; i++ {
  21.     go consumer(i, &wg, queue)
  22.   }
  23.   wg.Wait()
  24.   fmt.Println("Producer-Consumer example complete.")
  25. }
  26.  
  27. func consumer(id int, wg *sync.WaitGroup, queue <-chan int) {
  28.   defer wg.Done()
  29.   fmt.Println("Consumer", id, "started.")
  30.   for q := range queue {
  31.     fmt.Println("Consumer", id, "recieved:", q)
  32.     time.Sleep(time.Millisecond * 200)
  33.   }
  34.   fmt.Println("Consumer", id, "done.")
  35. }
  36.  
  37. func producer(wg *sync.WaitGroup, queue chan<- int, quantity int) {
  38.   defer close(queue)
  39.   defer wg.Done()
  40.   fmt.Println("Producer started.")
  41.   for i := 0; i < quantity; i++ {
  42.     queue<- i
  43.     fmt.Println("Producer - produced:", i)
  44.   }
  45.   fmt.Println("Producer done.")
  46. }
  47.  
Add Comment
Please, Sign In to add comment