【发布时间】:2015-11-15 16:29:45
【问题描述】:
我想知道。当我使用std::mutex _lock 并且想依靠守卫释放它时,我可以这样使用它吗?
class MyClass{
private:
mutable std::mutex _lock;
void subroutine(){/*...*/}
public:
void foo(){
std::lock(_lock);std::lock_guard<std::mutex> g(_lock, std::adopt_lock);
subroutine();
//require I still have the lock here
//...
return; //g goes out of scope ==> _lock is released
}
};
或者对subroutine 的调用是否已经导致锁被释放?如果是后者,我的选择是什么?
更新
这个案子呢?
class MyClass{
private:
mutable std::mutex _lock;
public:
void subroutine(){ //can be called on its own
std::lock(_lock);std::lock_guard<std::mutex> g(_lock, std::adopt_lock);
/*...*/
}
void foo(){
std::lock(_lock);std::lock_guard<std::mutex> g(_lock, std::adopt_lock);
subroutine();
//require I still have the lock here
//...
return; //g goes out of scope ==> _lock is released
}
};
【问题讨论】:
标签: c++ concurrency scope locking mutex