对锁定 boost 互斥锁的方式有疑问
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用lock_guard的优点是当超出范围时会释放锁。这样就无需手动释放锁,并减少了忘记释放锁的可能性。
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.
这两种形式根本不等同。这是与第二种形式等效的*:
这就是您所说的“仅”提供 RAII:避免可怕的样板文件以提供相同级别的正确性。
*:有注意事项;查看其他答案&评论
The two forms are not equivalent in the least. Here's what's equivalent* to the second form:
This is what you call "only" providing RAII: avoiding hideous boilerplate to provide the same level of correctness.
*: with caveats; see other answers & comments