Created
May 31, 2024 14:40
-
-
Save stokito/88ef0ed362993eb00a8ab7c7e0703bfd to your computer and use it in GitHub Desktop.
Golang sync.Cond example
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
package main | |
import ( | |
"context" | |
"sync" | |
"time" | |
) | |
func main() { | |
serverReadyCond := sync.NewCond(&sync.Mutex{}) | |
go func() { | |
println("waiter 1") | |
serverReadyCond.L.Lock() | |
serverReadyCond.Wait() | |
println("waiter 1 woke") | |
serverReadyCond.L.Unlock() | |
println("waiter 1 done") | |
}() | |
go func() { | |
println("waiter 2") | |
serverReadyCond.L.Lock() | |
serverReadyCond.Wait() | |
println("waiter 2 woke") | |
serverReadyCond.L.Unlock() | |
println("waiter 2 done") | |
}() | |
go func() { | |
println("server init") | |
time.Sleep(5 * time.Second) | |
serverReadyCond.L.Lock() | |
serverReadyCond.Broadcast() | |
println("server started") | |
serverReadyCond.L.Unlock() | |
println("server done") | |
}() | |
duration, _ := time.ParseDuration("30s") | |
ctx, _ := context.WithTimeout(context.Background(), duration) | |
<-ctx.Done() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment