Skip to content

Instantly share code, notes, and snippets.

@SamsadSajid
Created February 16, 2020 15:32
Show Gist options
  • Save SamsadSajid/c8fa018c95cffb4190435619fa1bd25d to your computer and use it in GitHub Desktop.
Save SamsadSajid/c8fa018c95cffb4190435619fa1bd25d to your computer and use it in GitHub Desktop.
Executing produce method
Recieved message The world itself's
Job "The world itself's" produced by worker 0
Message "The world itself's" is consumed by consumer 0 from worker 0
Recieved message just one big hoax.
Job "just one big hoax." produced by worker 0
Message "just one big hoax." is consumed by consumer 0 from worker 0
Recieved message
Recieved message
Found quit command
package main
import "fmt"
var messages = []string{
"The world itself's",
"just one big hoax.",
}
func execute(jobQ chan<- string, workerPool chan *producers, allDone chan<- bool) {
for _, j := range messages {
jobQ <- j
}
close(jobQ)
for _, w := range workers {
w.quit <- true
}
close(workerPool)
allDone <- true
}
func produce(jobQ <-chan string, p *producers, workerPool chan *producers) {
fmt.Println("Executing produce method")
for {
select {
case msg := <-jobQ:
fmt.Println("Recieved message ", msg)
{
workerPool <- p
if len(msg) > 0 {
fmt.Printf("Job \"%v\" produced by worker %v\n", msg, p.id)
}
p.myQ <- msg
}
case <-p.quit:
fmt.Println("Found quit command")
return
}
}
}
func consume(cIdx int, workerPool <-chan *producers) {
for {
worker := <-workerPool
if msg, ok := <-worker.myQ; ok {
if len(msg) > 0 {
fmt.Printf("Message \"%v\" is consumed by consumer %v from worker %v\n", msg, cIdx, worker.id)
}
}
}
}
const producerCount int = 1
const consumerCount int = 1
var workers []*producers
func main() {
jobQ := make(chan string)
allDone := make(chan bool)
workerPool := make(chan *producers)
go execute(jobQ, workerPool, allDone)
for i := 0; i < producerCount; i++ {
workers = append(workers, &producers{
myQ: make(chan string),
quit: make(chan bool),
id: i,
})
go produce(jobQ, workers[i], workerPool)
}
for i := 0; i < consumerCount; i++ {
go consume(i, workerPool)
}
<-allDone
}
type producers struct {
myQ chan string
quit chan bool
id int
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment