Skip to content

Instantly share code, notes, and snippets.

@stokito
Created May 31, 2024 14:40
Show Gist options
  • Save stokito/88ef0ed362993eb00a8ab7c7e0703bfd to your computer and use it in GitHub Desktop.
Save stokito/88ef0ed362993eb00a8ab7c7e0703bfd to your computer and use it in GitHub Desktop.
Golang sync.Cond example
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