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"
- "container/list"
- )
- type Stack struct {
- stack *list.List
- }
- func (s *Stack) Push(value int) {
- s.stack.PushFront(value)
- }
- func (s *Stack) Pop() (int, error) {
- if (s.stack.Len() > 0) {
- ele := s.stack.Front()
- s.stack.Remove(ele)
- return ele.Value.(int),nil
- }
- return 0,fmt.Errorf("Error: Nothing to Pop")
- }
- func (s *Stack) Empty() bool {
- return s.stack.Len() == 0
- }
- func main() {
- fmt.Println("Multi-Distributor-Consumer example starting.")
- distributors := 5
- consumers := 20
- buffer := 1
- var stack_mutex sync.Mutex
- stack := &Stack { stack: list.New() }
- for i := 0; i < 256; i++ {
- stack.Push(i)
- }
- queue := make(chan int, buffer)
- var dwg sync.WaitGroup
- dwg.Add(distributors)
- for i := 0; i < distributors; i++ {
- go distributor(i, &dwg, &stack_mutex, stack, queue)
- }
- var cwg sync.WaitGroup
- cwg.Add(consumers)
- for i := 0; i < consumers; i++ {
- go consumer(i, &cwg, queue)
- }
- dwg.Wait()
- close(queue)
- cwg.Wait()
- if (stack.Empty() != true) {
- fmt.Println("Something went wrong! Items are still on the stack!")
- } else { fmt.Println("Multi-Distributor-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 distributor(id int, wg *sync.WaitGroup, sm *sync.Mutex, s *Stack, queue chan<- int) {
- defer wg.Done()
- fmt.Println("Distributor", id, "started.")
- for {
- if s.Empty() {
- break;
- }
- // enter critical section
- sm.Lock()
- i,e := s.Pop()
- sm.Unlock()
- // leave critical section
- if e != nil {
- fmt.Println("Distributor", id, e)
- break;
- }
- queue<- i
- fmt.Println("Distributor", id, "produced:", i)
- }
- fmt.Println("Distributor", id, "done.")
- }
Add Comment
Please, Sign In to add comment