Skip to content

Instantly share code, notes, and snippets.

@bobisme
Created June 28, 2017 21:27
Show Gist options
  • Save bobisme/3c64b58394eaf30827703505c6ab1ca8 to your computer and use it in GitHub Desktop.
Save bobisme/3c64b58394eaf30827703505c6ab1ca8 to your computer and use it in GitHub Desktop.
Example use of Cond.Wait
package main
import (
"fmt"
"sync"
"time"
)
func waitForSignal() {
var m sync.Mutex
c := sync.NewCond(&m)
for i := 0; i < 10; i++ {
go func(i int){
m.Lock()
fmt.Println(i, "waiting")
c.Wait()
fmt.Println(i, "got a signal")
m.Unlock()
}(i)
}
fmt.Println("waiting for things to start")
time.Sleep(1 * time.Second)
fmt.Println("sending a signal which will awaken 1 goroutine")
c.Signal()
}
func waitForBroadcast() {
var m sync.Mutex
c := sync.NewCond(&m)
for i := 10; i < 20; i++ {
go func(i int){
m.Lock()
fmt.Println(i, "waiting")
c.Wait()
fmt.Println(i, "got a signal")
m.Unlock()
}(i)
}
fmt.Println("waiting for things to start")
time.Sleep(1 * time.Second)
fmt.Println("sending a broadcast which will awaken all goroutines")
c.Broadcast()
}
func main() {
waitForSignal()
fmt.Println("waiting to make sure no others signal")
time.Sleep(1 * time.Second)
waitForBroadcast()
fmt.Println("\n\nsleeping to trigger a context switch...")
time.Sleep(500 * time.Millisecond)
fmt.Println("all 10-20 should have gotten that signal")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment