有条件的 RAII 锁定
我有一段代码,仅当某些条件成立时才需要用锁保护。
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以切换为使用
std::unique_lock
并使用其std::defer_lock_t
标记的构造函数。这将从互斥锁解锁开始,但您可以使用其lock ()
方法来锁定互斥锁,然后析构函数将释放该互斥锁。这将为您提供如下所示的代码流:You can switch to using a
std::unique_lock
and use itsstd::defer_lock_t
tagged constructor. This will start with the mutex unlocked, but you can then use itslock()
method to lock the mutex, which will then be released by the destructor. That would give you a code flow that looks like this:如果您不想编写另一个函数,您可以使用这样的虚拟锁。请注意,获取虚拟锁并不重要,因为它是局部变量。
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.