有条件的 RAII 锁定

发布于 2025-01-17 00:34:50 字数 441 浏览 2 评论 0原文

我有一段代码,仅当某些条件成立时才需要用锁保护。

if(condition) {

   std::lock_guard<std::mutex> guard(some_mutex);

   // do a bunch of things

} else {

   // do a bunch of things
}

虽然我可以将所有 // 一堆东西 移动到一个单独的函数中并调用它,但我想知道是否有一种 RAII 方法可以允许有条件地获取锁定。

像这样的东西

if(condition){

   // the lock is taken
}

// do a bunch of things

// lock is automatically released if it was taken

I have a piece of code which needs to be protected by a lock only if some condition is true.

if(condition) {

   std::lock_guard<std::mutex> guard(some_mutex);

   // do a bunch of things

} else {

   // do a bunch of things
}

Although I can move all of the // bunch of things in a separate function and call that, I was wondering if there is an RAII way that would allow to take the lock conditionally.

Something like

if(condition){

   // the lock is taken
}

// do a bunch of things

// lock is automatically released if it was taken

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

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

发布评论

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

评论(2

究竟谁懂我的在乎 2025-01-24 00:34:50

您可以切换为使用 std::unique_lock 并使用其 std::defer_lock_t 标记的构造函数。这将从互斥锁解锁开始,但您可以使用其 lock () 方法来锁定互斥锁,然后析构函数将释放该互斥锁。这将为您提供如下所示的代码流:

{
    std::unique_lock<std::mutex> guard(some_mutex, std::defer_lock_t{});
    if (mutex_should_be_locked)
    {
        guard.lock();
    }
    // rest of code 
} // scope exit, unlock will be called if the mutex was locked

You can switch to using a std::unique_lock and use its std::defer_lock_t tagged constructor. This will start with the mutex unlocked, but you can then use its lock() method to lock the mutex, which will then be released by the destructor. That would give you a code flow that looks like this:

{
    std::unique_lock<std::mutex> guard(some_mutex, std::defer_lock_t{});
    if (mutex_should_be_locked)
    {
        guard.lock();
    }
    // rest of code 
} // scope exit, unlock will be called if the mutex was locked
放手` 2025-01-24 00:34:50

如果您不想编写另一个函数,您可以使用这样的虚拟锁。请注意,获取虚拟锁并不重要,因为它是局部变量。

 std::shared_mutex dummy_lock;
 std::shared_lock<std::shared_mutex> lock(
    acquire_lock ? original_lock : dummy_lock);

If you do not want to write another function you can use a dummy lock like this. Note that acquiring the dummy lock is inconsequential as it's a local variable.

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