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.

Revisions

  1. stokito created this gist May 31, 2024.
    43 changes: 43 additions & 0 deletions go_cond_example.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    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()
    }