开发者

Lock hierarchies and reader-writer mutexes

开发者 https://www.devze.com 2023-03-03 00:46 出处:网络
Suppose I use a lock hierarchy to avoid deadlock. If I use reader-writer mutexes, how should I think about and use these? Do there exist (can I think of) a distinct reading lock and writing lock in th

Suppose I use a lock hierarchy to avoid deadlock. If I use reader-writer mutexes, how should I think about and use these? Do there exist (can I think of) a distinct reading lock and writing lock in the hierarchy for each reader-writer mutex? (If yes, this would imply that these two locks could be assigned different levels in the hierarchy.) Does using reader-write mutexes introduce possibilities of deadlock into the hierarchy? (If yes, how (if at all) can that be avoided?) What about "upgradeable" locks (reader locks which can be turned into writer locks without unlocking the mutex first)?

Yes, I've seen advice to avoid (specifically reader-writer) mutexes if possible. This is not about whether to use them generally; just assume that there existed a problem best solved by reader-writer mutexes. Similarly, do not suggest alternatives to the lock hierarchy just because you'd generally favour them. (If however combin开发者_高级运维ing reader-writer mutexes with lock hierarchies does introduce a possibility of deadlocks, feel free to suggest alterations to the used concepts.)

It might be helpful to know that I'm thinking about multi-threaded programs using the Boost Thread library. The reader-writer mutex class is called shared_mutex there; unique_lock is an exclusive (writer) lock; shared_lock is a shared (reader) lock; upgrade_lock is a reader lock that can temporarily be upgraded to a writer lock.


You have to treat it as a single lock for the purposes of lock ordering. If you have lock A and a R-W lock B, and have two threads that do this:

  1. lock A, wait for read(B)
  2. lock write(B), wait for A

they will still deadlock.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号