Skip to content

Instantly share code, notes, and snippets.

@fcracker79
Created August 2, 2023 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcracker79/1ce73133c3490db0ffc314d38cf4a3ef to your computer and use it in GitHub Desktop.
Save fcracker79/1ce73133c3490db0ffc314d38cf4a3ef to your computer and use it in GitHub Desktop.
Errata Concurrency in Go chapter 3, page 56
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