Using a lock with condition variables

懵懂的女人 提交于 2019-12-04 13:24:27

Yes you do, and using atomic is not sufficient.

CVs for efficiency can be woken spuriously, and those spurious lookups (or similar issues) can cause a write to be missed.

Imagine a spurious wake up. The recieving thread checks the bool, sees nothing (false), then is preempted. Someone notify all's and sets the bool. The notification is discarded, as the recieving thread is already processing one. The recieving thread now completes, and misses the message.

Now, add a lock in the sender that overlaps some time sequenced after the bool is set and before the cv notification. This communicaton hole no longer exists.

(Even without spurious wakeups, multiple notifications can cause similar problems sometimes.)

You do not have to hold the lock while notifying (and in fact this is a pessimization), but the lock must be held post-write and pre-notify for some period, in general.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!