Skip to content

Instantly share code, notes, and snippets.

@larzconwell
Last active Feb 5, 2018
Embed
What would you like to do?
package main
import (
"fmt"
"sync"
"time"
)
var tasks []int
var wg sync.WaitGroup
var mu sync.Mutex
var cond = sync.NewCond(&mu)
var done = make(chan bool)
func consumer(id int) {
for {
cond.L.Lock()
for len(tasks) == 0 {
cond.Wait()
select {
case <-done:
fmt.Println("Consumer", id, "got signal")
cond.L.Unlock()
return
default:
}
}
task := tasks[0]
tasks = tasks[1:]
cond.L.Unlock()
fmt.Println("Consuming value", task, "from consumer", id)
}
}
func producer() {
i := 0
for {
select {
case <-done:
fmt.Println("Producer got signal")
return
default:
}
cond.L.Lock()
fmt.Println("Producing value", i)
tasks = append(tasks, i)
cond.Signal()
cond.L.Unlock()
i++
<-time.After(500 * time.Millisecond)
}
}
func main() {
n := 5
wg.Add(n + 1)
for i := 0; i < n; i++ {
go func(i int) {
consumer(i)
wg.Done()
}(i)
}
go func() {
producer()
wg.Done()
}()
<-time.After(10 * time.Second)
close(done)
cond.Broadcast()
fmt.Println("Signaled done")
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment