我在 O'Reilly 的一次培训中看到了这个例子。有一个条件应该可以防止 widgetInventory 变为负值。示例有效,但我不明白为什么当 makeSales 获取互斥体且 widgetInventory 为 0 时程序不会死锁。
var ( wg sync.WaitGroup mutex = sync.Mutex{} widgetInventory int32= 1000 newPurchase = sync.NewCond(&mutex) ) func main() { fmt.Println("Starting inventory count = ", widgetInventory) wg.Add(2) go makeSales() go newPurchases() wg.Wait() fmt.Println("Ending inventory count = ", widgetInventory) } func makeSales() { for i := 0; i < 3000; i++ { mutex.Lock() if widgetInventory-100 < 0{ newPurchase.Wait() } widgetInventory -= 100 fmt.Println(widgetInventory) mutex.Unlock() } wg.Done() } func newPurchases() { for i := 0; i < 3000; i++ { mutex.Lock() widgetInventory+= 100 fmt.Println(widgetInventory) newPurchase.Signal() mutex.Unlock() } wg.Done() }
当 makeSales 获取互斥体而 widgetInventory 为 0 时,我预计代码会死锁。
我没有注意到条件与互斥体相关联:
newPurchase =sync.NewCond(&mutex)
输入 .Wait() 会解锁互斥锁,并在收到条件信号后尝试重新获取它。
condition.Wait() 仅在获取互斥体时才能使用,因此它的工作代价是代码的可读性不那么高:-)