Skip to content

Instantly share code, notes, and snippets.

@mochow13
Created January 29, 2020 15:56
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mochow13/74ee57078d58536929575ab481dd9693 to your computer and use it in GitHub Desktop.
Save mochow13/74ee57078d58536929575ab481dd9693 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
var messages = [][]string{
{
"The world itself's",
"just one big hoax.",
"Spamming each other with our",
"running commentary of bullshit,",
},
{
"but with our things, our property, our money.",
"I'm not saying anything new.",
"We all know why we do this,",
"not because Hunger Games",
"books make us happy,",
},
{
"masquerading as insight, our social media",
"faking as intimacy.",
"Or is it that we voted for this?",
"Not with our rigged elections,",
},
{
"but because we wanna be sedated.",
"Because it's painful not to pretend,",
"because we're cowards.",
"- Elliot Alderson",
"Mr. Robot",
},
}
const producerCount int = 4
const consumerCount int = 3
func produce(link chan<- string, id int, wg *sync.WaitGroup) {
defer wg.Done()
for _, msg := range messages[id] {
link <- msg
}
}
func consume(link <-chan string, id int, wg *sync.WaitGroup) {
defer wg.Done()
for msg := range link {
fmt.Printf("Message \"%v\" is consumed by consumer %v\n", msg, id)
}
}
func main() {
link := make(chan string)
wp := &sync.WaitGroup{}
wc := &sync.WaitGroup{}
wp.Add(producerCount)
wc.Add(consumerCount)
for i := 0; i < producerCount; i++ {
go produce(link, i, wp)
}
for i := 0; i < consumerCount; i++ {
go consume(link, i, wc)
}
wp.Wait()
close(link)
wc.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment