-
-
Save 0xack13/124c67961da555e55f93c388bab5dac2 to your computer and use it in GitHub Desktop.
GoLang: How to use sync.Cond
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 ( | |
| "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