对锁定 boost 互斥锁的方式有疑问

发布于 2024-11-24 22:57:58 字数 207 浏览 7 评论 0原文

boost::recursive_mutex m;
m.lock();

boost::lock_guard<boost::recursive_mutex> lock( mutex_ );

使用第一种形式相比有优势吗?第二种形式只提供RAII机制,还是还有其他优点?

boost::recursive_mutex m;
m.lock();

versus

boost::lock_guard<boost::recursive_mutex> lock( mutex_ );

Is there an advantage to use the first Form? Does the second form only provide RAII mecanism, or are there others advantages ?

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

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

发布评论

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

评论(2

回眸一笑 2024-12-01 22:57:58

使用lock_guard的优点是当超出范围时会释放锁。这样就无需手动释放锁,并减少了忘记释放锁的可能性。

boost::recursive_mutex mylock;

{
    boost::lock_guard<boost::recursive_mutex> lock( mylock );

    // do something

    if(false == do_something())
    {
        return; // "lock" goes out of scope and unlocks 'mylock' from it's destructor.
    }

}
// "lock" has gone out of scope and unlocked 'mylock' from it's destructor.

The advantage of using lock_guard is that it will release the lock when it goes out of scope. This eliminates the need to manually release the lock and reduces the chance of forgetting to do so.

boost::recursive_mutex mylock;

{
    boost::lock_guard<boost::recursive_mutex> lock( mylock );

    // do something

    if(false == do_something())
    {
        return; // "lock" goes out of scope and unlocks 'mylock' from it's destructor.
    }

}
// "lock" has gone out of scope and unlocked 'mylock' from it's destructor.
秋凉 2024-12-01 22:57:58

这两种形式根本不等同。这是与第二种形式等效的*:

boost::recursive_mutex m;
m.lock();
try {
    // ...
} catch(...) {
    m.unlock();
    throw;
}
m.unlock();

这就是您所说的“仅”提供 RAII:避免可怕的样板文件以提供相同级别的正确性。

*:有注意事项;查看其他答案&评论

The two forms are not equivalent in the least. Here's what's equivalent* to the second form:

boost::recursive_mutex m;
m.lock();
try {
    // ...
} catch(...) {
    m.unlock();
    throw;
}
m.unlock();

This is what you call "only" providing RAII: avoiding hideous boilerplate to provide the same level of correctness.

*: with caveats; see other answers & comments

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