如何解锁 boost::upgrade_to_unique_lock (由 boost::shared_mutex 制成)?

发布于 2024-12-09 01:59:37 字数 365 浏览 0 评论 0原文

所以我有一些shared_mutex并做到了这一点:

        boost::upgrade_lock<boost::shared_mutex> lock(f->mutex);
        boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);

现在我想“解锁它”或者至少将其降级为类似的东西:

boost::shared_lock<boost::shared_mutex> lock_r(f->mutex);

如何做这样的事情?是否可以?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

独自←快乐 2024-12-16 01:59:37

如果您让 upgrade_to_unique_lock 超出范围,它将自动降级回升级所有权。

例如

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
}

编辑:另一件事。如果给定函数仅需要独占锁,则可以使用 boost::unique_lock 并唯一锁定,而无需同时使用 upgradeupgrade_to_unique 锁。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文