Created
November 16, 2018 00:31
-
-
Save ianfoo/d0e0bf08ed5d884936ca16584dfa7ce0 to your computer and use it in GitHub Desktop.
How to use Go's sync.Condition
This file contains hidden or 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
| // 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