Skip to content

Instantly share code, notes, and snippets.

@yumed15
Created November 22, 2023 12:15
Show Gist options
  • Save yumed15/1cd45c53815e8145745ba1b12cdd4066 to your computer and use it in GitHub Desktop.
Save yumed15/1cd45c53815e8145745ba1b12cdd4066 to your computer and use it in GitHub Desktop.
type Button struct { // contains a condition
Clicked *sync.Cond
}
button := Button{Clicked: sync.NewCond(&sync.Mutex{})}
subscribe := func(c *sync.Cond, fn func()) { // allows us to register functions
var goroutineRunning sync.WaitGroup // to handle signals from conditions
goroutineRunning.Add(1)
go func() {
goroutineRunning.Done()
c.L.Lock()
defer c.L.Unlock()
c.Wait()
fn()
}()
goroutineRunning.Wait()
}
var clickRegistered sync.WaitGroup
clickRegistered.Add(3)
subscribe(button.Clicked, func() {
// do smth
clickRegistered.Done()
})
subscribe(button.Clicked, func() {
// do smth
clickRegistered.Done()
})
subscribe(button.Clicked, func() {
// do smth
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