Starvation with upgrade_lock

耗尽温柔 提交于 2019-12-04 10:35:40
ComicSansMS

This is a subtle one. The difference involves the concepts of shared and upgradable ownerships, and their implementations in Boost.

Let's first get the concepts of shared ownership and upgradable ownership sorted out. For a SharedLockable, a thread must decide beforehand whether it wants to change the object (requiring exclusive ownership) or only read from it (shared ownership suffices). If a thread with shared ownership decides it wants to change the object, it first must release its shared lock on the object and then construct a new, exclusive lock. In between these two steps, the thread holds no locks at all on the object. Attempting to construct an exclusive lock from a thread that already holds a shared lock will deadlock, as the exclusive lock constructor will block until all shared locks have been released.

UpgradeLockable overcomes this limitation, by allowing to upgrade a shared lock to an exclusive lock without releasing it. That is, the thread keeps an active lock on the mutex at all times, prohibiting other threads from obtaining an exclusive lock in the meantime. Besides that, UpgradeLockable still allows all operations from SharedLockable, the former concept is a superset of the latter. The question you linked to is only concerned with the SharedLockable concept.

Neither concept, as specified by Boost, requires an implementation to be fair. However, the shared_mutex, which is Boost's minimal implementation for a SharedLockable does give the fairness guarantees quoted in your question. Note that this is an additional guarantee to what the concept actually requires.

Unfortunately, the minimal implementation for upgradable ownership, the upgrade_mutex, does not give this additional gurantee. It still implements the shared ownership concept as a requirement for upgradable ownership, but since fairness is not required for a conforming implementation, they do not provide it.

As pointed out by Howard in the comments, Terekhov's algorithm can be trivially adjusted to work with upgradable locks as well, it's just that the Boost implementation does not support this currently.

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