我有一个应用程序,我正在创建多个 goroutine 来同时执行某个任务。所有工作协程都会等待条件/事件发生,一旦事件被触发,它们就会开始执行。创建完所有goroutines后,主线程在发送广播信号之前应该知道所有goroutines确实处于等待状态。
我知道这可以使用通道来完成(这是推荐的),但我也发现 go 的同步包很有趣。只是想弄清楚如何使用同步包而不是通道来实现相同的功能
package main
import (
"fmt"
"sync"
"time"
)
var counter int
func worker(wg *sync.WaitGroup, cond *sync.Cond, id int) {
fmt.Println("Starting Goroutine ID:", id)
// Get a lock and wait
cond.L.Lock()
defer cond.L.Unlock()
fmt.Println("Goroutine with ID: ", id, "obtained a lock")
// Do some processing with the shared resource and wait
counter++
wg.Done()
cond.Wait()
fmt.Println("Goroutine ID:", id, "signalled. Continuing...")
}
func main() {
var wg sync.WaitGroup
cond := sync.NewCond(&sync.Mutex{})
counter = 0
for i := 0; i < 5; i++ {
wg.Add(1)
go worker(&wg, cond, i)
}
wg.Wait() // Wait()'ing only until the counter is incremented
// How to make sure that all goroutines you created are indeed wait()'ing ?????
cond.Broadcast()
time.Sleep(2 * time.Second)
cond.Broadcast()
fmt.Println("Final value of the counter is", counter)
}
如果我在最后 3 行中不使用以下语句(fmt.Println 除外)
time.Sleep(2 * time.Second)
cond.Broadcast()
我得到以下输出..
Starting Goroutine ID: 4
Goroutine with ID: 4 obtained a lock
Starting Goroutine ID: 3
Goroutine with ID: 3 obtained a lock
Starting Goroutine ID: 1
Goroutine with ID: 1 obtained a lock
Starting Goroutine ID: 0
Goroutine with ID: 0 obtained a lock
Starting Goroutine ID: 2
Goroutine with ID: 2 obtained a lock
Final value of the counter is 5
Goroutine ID: 3 signalled. Continuing...
理想情况下,每个 goroutine 都应该能够打印
Goroutine ID: 3 signalled. Continuing...
以及相应的 goroutine id。我们无法打印它,因为并非所有 goroutine 都发出信号,因为其中一些 goroutine 甚至没有处于等待状态。这就是我添加 time.Sleep 的原因,这不是一个实际的解决方案。
我的问题是..我怎么知道所有的goroutine实际上都在等待条件cond.Wait()..Channels是一个解决方案,但我想知道如何使用go的sync包来做到这一点?