Lock hierarchies and reader-writer mutexes
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:
- lock A, wait for read(B)
- lock write(B), wait for A
they will still deadlock.
精彩评论