Created
February 8, 2019 10:42
-
-
Save kirugan/85956ce784550675abf22fee4d73ace4 to your computer and use it in GitHub Desktop.
sync.Cond demonstration
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() { | |
nConnections := 10 | |
var wg sync.WaitGroup | |
wg.Add(nConnections) | |
cond := sync.NewCond(&sync.Mutex{}) | |
for i := 0; i < nConnections; i++ { | |
go func(i int) { | |
fmt.Println("Before lock ", i) | |
cond.L.Lock() | |
fmt.Println("Before wait ", i) | |
cond.Wait() | |
fmt.Println("Here i am", i) | |
cond.L.Unlock() | |
fmt.Println("After unlock ", i) | |
wg.Done() | |
}(i) | |
} | |
fmt.Println("Sleeping...") | |
time.Sleep(time.Second * 1) | |
fmt.Println("Storm!") | |
cond.Broadcast() | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment