我有一个互斥体的问题...
这是我的代码的一般结构:
#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() 进行两次解锁是否会产生不良行为?
最佳答案
这就是为什么 C++ 有单独的锁和互斥类:锁是一个方便的 RAII 类,即使在抛出异常或其他白痴程序员添加新的 return
时,它也会确保你的互斥锁被解锁>/break
/continue
进入程序。以下是该程序如何与 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);
}
关于c++ - if 条件下的互斥量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20586654/