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("Producer-Consumer example starting.")
- quantity := 30
- consumers := 3
- buffer := 3
- queue := make(chan int, buffer)
- var wg sync.WaitGroup
- wg.Add(consumers + 1)
- go producer(&wg, queue, quantity)
- for i := 0; i < consumers; i++ {
- go consumer(i, &wg, queue)
- }
- wg.Wait()
- fmt.Println("Producer-Consumer example complete.")
- }
- func consumer(id int, wg *sync.WaitGroup, queue <-chan int) {
- defer wg.Done()
- fmt.Println("Consumer", id, "started.")
- for q := range queue {
- fmt.Println("Consumer", id, "recieved:", q)
- time.Sleep(time.Millisecond * 200)
- }
- fmt.Println("Consumer", id, "done.")
- }
- func producer(wg *sync.WaitGroup, queue chan<- int, quantity int) {
- defer close(queue)
- defer wg.Done()
- fmt.Println("Producer started.")
- for i := 0; i < quantity; i++ {
- queue<- i
- fmt.Println("Producer - produced:", i)
- }
- fmt.Println("Producer done.")
- }
Add Comment
Please, Sign In to add comment