我对互斥锁有个问题...
这是我的代码的一般结构:
#include <mutex>
std::mutex m;
While(1){
m.lock();
if(global_variable1==1){
//CODE GOES HERE
if (err==error::eof){
cout<<"error!"<<endl;
//should I put a m.unlock() here??
continue;
}
int something=1;
global_variable2=something;
}
m.unlock();
usleep(100000);
}基本上,我想安全地更改全局变量,所以我认为我需要使用互斥锁。我应该只在" if (global_variable1==1)“函数之后解锁互斥锁,但是如果有错误,互斥锁将不会被解锁。我可以在“继续”前解锁吗?或者这会搞砸其他的事情吗?对同一个mutex.lock()进行两次解锁会有不受欢迎的行为吗?
发布于 2013-12-15 02:56:05
这就是为什么C++有单独的锁和互斥锁类的原因:锁是一个方便的RAII类,它将确保互斥锁被解锁,即使在抛出异常或其他愚蠢的程序员向程序中添加新的锁的时候也是如此。下面是这个程序如何与std::unique_lock一起工作
#include <mutex>
std::mutex m;
While(1){
std::unique_lock<std::mutex> lock(m);
if(global_variable1==1){
//CODE GOES HERE
if (err==error::eof){
cout<<"error!"<<endl;
continue;
}
int something=1;
global_variable2=something;
}
lock.unlock();
usleep(100000);
}发布于 2013-12-15 03:02:47
Do not锁定/解锁互斥锁手动!取而代之的是使用守卫,例如std::lock_guard<std::mutex>:守卫将在构造时获取锁,并在销毁时释放它。要限制锁的持有时间,只需使用一个块:
while (true) {
{
std::lock_guard<std::mutex> cerberos(m);
// ...
}
sleep(n);
}https://stackoverflow.com/questions/20586654
复制相似问题