Created
August 2, 2023 06:40
-
-
Save fcracker79/1ce73133c3490db0ffc314d38cf4a3ef to your computer and use it in GitHub Desktop.
Errata Concurrency in Go chapter 3, page 56
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" | |
) | |
type Button struct { | |
Clicked *sync.Cond | |
} | |
func main() { | |
button := Button {Clicked: sync.NewCond(&sync.Mutex{})} | |
subscribe := func(c *sync.Cond, fn func()) { | |
var goroutineRunning sync.WaitGroup | |
goroutineRunning.Add(1) | |
go func() { | |
goroutineRunning.Done() | |
// Simulating a delay during the execution of the goroutine <---------------------------------- | |
time.Sleep(1 * time.Second) | |
c.L.Lock() | |
defer c.L.Unlock() | |
c.Wait() | |
fn() | |
}() | |
goroutineRunning.Wait() | |
} | |
var clickRegistered sync.WaitGroup | |
clickRegistered.Add(3) | |
subscribe(button.Clicked, func() { | |
fmt.Println("Maximizing window.") | |
clickRegistered.Done() | |
}) | |
subscribe(button.Clicked, func() { | |
fmt.Println("Displaying annoying dialog box!") | |
clickRegistered.Done() | |
}) | |
subscribe(button.Clicked, func() { | |
fmt.Println("Mouse clicked.") | |
clickRegistered.Done() | |
}) | |
button.Clicked.Broadcast() | |
clickRegistered.Wait() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment