Skip to content

Instantly share code, notes, and snippets.

@ianfoo
Created November 16, 2018 00:31
Show Gist options
  • Select an option

  • Save ianfoo/d0e0bf08ed5d884936ca16584dfa7ce0 to your computer and use it in GitHub Desktop.

Select an option

Save ianfoo/d0e0bf08ed5d884936ca16584dfa7ce0 to your computer and use it in GitHub Desktop.
How to use Go's sync.Condition
// How to use sync.Condition
// https://play.golang.org/p/IdIkQ6S5ZlV
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var (
loadWg, finishWg sync.WaitGroup
mu sync.Mutex
cond = sync.NewCond(&mu)
)
for i := 0; i < 5; i++ {
loadWg.Add(1)
finishWg.Add(1)
go func(i int) {
fmt.Printf("%d waiting\n", i)
cond.L.Lock()
loadWg.Done()
cond.Wait()
cond.L.Unlock()
time.Sleep(500 * time.Millisecond)
fmt.Printf("%d finished\n", i)
finishWg.Done()
}(i)
}
loadWg.Wait()
fmt.Println("waking goroutines")
cond.Broadcast()
finishWg.Wait()
fmt.Println("all goroutines finished")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment