package main
import (
"fmt"
"sync"
"time"
)
var M sync.Mutex = sync.Mutex{}
var C *sync.Cond = sync.NewCond(&M)
func ff(){
M.Lock()
C.Wait()
fmt.Println("broadcasting")
M.Unlock()
}
func main() {
num := [6]int{}
for _, _= range num {
go ff()
}
M.Lock()
C.Broadcast()
M.Unlock()
fmt.Println("done")
time.Sleep(5 * time.Second)
}
最佳答案
如评论中所述,对广播的调用可能发生在 goroutines 到达 C.Wait()
之前
您可以使用 sync 包的另一部分来解决这个问题。一个 WaitGroup
package main
import (
"fmt"
"sync"
"time"
)
var M sync.Mutex
var C *sync.Cond = sync.NewCond(&M)
var wg sync.WaitGroup // create a wait group
func ff(){
wg.Done() // tell the group that one routine has started
M.Lock()
C.Wait()
fmt.Println("broadcasting")
M.Unlock()
}
func main() {
num := [6]int{}
wg.Add(len(num)) // tell the group you are waiting for len(num) goroutines to start
for _, _= range num {
go ff()
}
M.Lock()
wg.Wait() // wait for all the routines to start
C.Broadcast()
M.Unlock()
fmt.Println("done")
time.Sleep(5 * time.Second)
}
还有;在调用 C.Broadcast()
时,您不一定需要锁定 M sync.Mutex
来自文档:
It is allowed but not required for the caller to hold c.L during the call.