https://go.dev/play/p/YVYRWSgcp4u
我在“开发人员的 Go 工具和技术中的并发性”中看到了这段代码,其中提到了广播的用法,上下文是使用广播来唤醒三个 gorouting。
package main
import (
"fmt"
"sync"
"time"
)
func main() {
type Button struct {
Clicked *sync.Cond
}
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() // <---- why here?
//fmt.Println("wg already done")
c.L.Lock()
defer c.L.Unlock()
c.Wait()
fn()
//goroutineRunning.Done(), if put here will result in deadlock, why?
}()
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()
})
time.Sleep(time.Second * 3)
button.Clicked.Broadcast()
clickRegistered.Wait()
}
我正在尝试了解订阅部分
subscribe := func(c *sync.Cond, fn func()) {
var goroutineRunning sync.WaitGroup
goroutineRunning.Add(1)
go func() {
goroutineRunning.Done()
//fmt.Println("wg already done")
c.L.Lock()
defer c.L.Unlock()
c.Wait()
fn()
//goroutineRunning.Done()
//fmt.Println("fn executed")
}()
goroutineRunning.Wait()
}
作者说:
在这里,我们定义了一个便利函数,它允许我们注册函数来处理来自条件的信号。每个处理程序都在自己的 goroutine 上运行,并且在确认该 goroutine 正在运行之前订阅不会退出。
我的理解是,我们应该defer goroutingRunning.Done()
在 gorouting 内部,以便后续代码(包括等待 Cond 和 fn() 调用,将有机会运行),但是在这种情况下,似乎goroutingRunning.Done()
必须在 gorouting 的开头,否则它会导致死锁错误,但为什么呢?