C++ boost::upgrade_lock boost::upgrade_to_unique_lock如何使用 例子
Posted 软件工程小施同学
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ boost::upgrade_lock boost::upgrade_to_unique_lock如何使用 例子相关的知识,希望对你有一定的参考价值。
upgrade_lock将可将读锁(shared_lock)升级为upgrade_lock,与shared_lock不互斥,与别的upgrade_lock和unique_lock互斥。
也就是说线程A获得mutex的upgrade_lock后,线程B、C等还可以获得mutex的share_mutex,反之亦然。
upgrade_to_unique_lock可将upgrade_lock升级为独占锁,不允许其它线程读或写
question
So I had some shared_mutex and done this:
boost::upgrade_lock<boost::shared_mutex> lock(f->mutex); boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
now I want to "unlock it" or at least downgrade it to something like:
boost::shared_lock<boost::shared_mutex> lock_r(f->mutex);
How to do such thing? Is it possible?
solution
If you let the upgrade_to_unique_lock go out of scope, it will automatically downgrade back to upgrade ownership.
For example
void foo() { boost::upgrade_lock<boost::shared_mutex> lock(f->mutex); // Do shared operations, as mutex is held upgradeable // ... if(need_to_get_unique) { boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock); // Do exclusive operations, as mutex is held uniquely // ... // At end of scope unique is released back to upgradeable } // Only shared operations here, as it's only held upgradeable // ... // At end of scope mutex is completely released }
Edit: One other thing. If a given function only requires exclusive locks, you can use boost::unique_lock and lock uniquely, without going through both the upgrade and upgrade_to_unique locks.
如何解锁boost :: upgrade_to_unique_lock(由boost :: shared_mutex制成)? - IT屋-程序员软件开发技术分享社区
以上是关于C++ boost::upgrade_lock boost::upgrade_to_unique_lock如何使用 例子的主要内容,如果未能解决你的问题,请参考以下文章