Created
May 3, 2020 02:33
-
-
Save tuongaz/fd6bbc9b8ab16adb37fe56b547a238d8 to your computer and use it in GitHub Desktop.
Example of using sync.Cond and broadcast feature
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 ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
// Listen for broadcast. | |
// The wg waitgroup is to make sure the listen func is called before the broadcast happens. | |
func listen(name string, c *sync.Cond, wg *sync.WaitGroup) { | |
fmt.Println(name + " started") | |
wg.Done() | |
c.L.Lock() | |
c.Wait() | |
fmt.Println(name + " was called") | |
c.L.Unlock() | |
} | |
// Send broadcast | |
func broadcast(c *sync.Cond, wg *sync.WaitGroup) { | |
fmt.Println("broadcast started") | |
c.L.Lock() | |
c.Broadcast() | |
c.L.Unlock() | |
time.Sleep(1 * time.Second) | |
wg.Done() | |
} | |
func main() { | |
cond := sync.NewCond(&sync.Mutex{}) | |
wg := &sync.WaitGroup{} | |
wg.Add(2) | |
go listen("Listener 1", cond, wg) | |
go listen("Listener 2", cond, wg) | |
wg.Wait() | |
wg.Add(1) | |
go broadcast(cond, wg) | |
wg.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment