Created
August 23, 2018 14:02
-
-
Save xigh/2bf887ad5541718c605288473cc2f946 to your computer and use it in GitHub Desktop.
How to use Golang sync/cond
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" | |
) | |
func main() { | |
c := sync.NewCond(&sync.Mutex{}) | |
wg := &sync.WaitGroup{} | |
fmt.Printf("M: launching 'waiters'\n") | |
for i := 0; i < 10; i++ { | |
wg.Add(1) | |
go func(i int) { | |
defer wg.Done() | |
fmt.Printf("%d: waiting cond\n", i) | |
c.L.Lock() | |
defer c.L.Unlock() | |
c.Wait() | |
fmt.Printf("%d: released\n", i) | |
}(i) | |
} | |
fmt.Printf("M: waiting 2s\n") | |
time.Sleep(2 * time.Second) | |
for i := 0; i < 3; i++ { | |
fmt.Printf("M: signal and wait 2s\n") | |
c.Signal() | |
time.Sleep(2 * time.Second) | |
} | |
fmt.Printf("M: broadcasting\n") | |
c.Broadcast() | |
fmt.Printf("M: waiting 'waiters' to finish\n") | |
wg.Wait() | |
fmt.Printf("M: waiting 2s\n") | |
time.Sleep(2 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment