Last active
February 5, 2018 04:19
-
-
Save larzconwell/eeff74277c9648f4db43e8805aae5b9b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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