How to unlock boost::upgrade_to_unique_lock (made from boost::shared_mutex)?

旧时模样 提交于 2019-12-14 01:28:41

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/7704870/how-to-unlock-boostupgrade-to-unique-lock-made-from-boostshared-mutex

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