Skip to content

Instantly share code, notes, and snippets.

@fracasula
Created August 3, 2018 14:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fracasula/21565ea1cf0c15726ca38736031edc70 to your computer and use it in GitHub Desktop.
Save fracasula/21565ea1cf0c15726ca38736031edc70 to your computer and use it in GitHub Desktop.
GoLang: How to use sync.Cond
package main
import (
"sync"
"fmt"
"time"
)
func main() {
lock := sync.Mutex{}
lock.Lock()
cond := sync.NewCond(&lock)
waitGroup := sync.WaitGroup{}
waitGroup.Add(2)
go func() {
defer waitGroup.Done()
fmt.Println("First go routine has started and waits for 1 second before broadcasting condition")
time.Sleep(1 * time.Second)
fmt.Println("First go routine broadcasts condition")
cond.Broadcast()
}()
go func() {
defer waitGroup.Done()
fmt.Println("Second go routine has started and is waiting on condition")
cond.Wait()
fmt.Println("Second go routine unlocked by condition broadcast")
}()
fmt.Println("Main go routine starts waiting")
waitGroup.Wait()
fmt.Println("Main go routine ends")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment