【发布时间】:2019-09-18 07:40:17
【问题描述】:
我有课
class Device
{
enum State {eStopped, eRunning}
State flag = eStopped;
public:
void run(){
if(flag==eRunning){return;}
/*some codes to start this device*/
flag = eRunning;
}
void stop(){
if(flag==eStopped){return;}
/*some codes to stop this device*/
flag = eStopped;
}
void doMaintenance(){
if(flag==eRunning){return;} // We can't do maintenance when the device is running
/*Here, the flag may be modified to eRunning in other threads*/
}
}
在doMaintenance()函数中,flag会在(flag==eRunning)检查后被其他线程改变。如何优雅地防止这种情况发生?
【问题讨论】:
-
您要完全阻止它还是只是确保读/写同步?
-
@rustyx std::mutex 用于锁定相同代码块。在这种情况下,为 doMaintenance 添加互斥锁并不能帮助其他函数修改标志。
-
不让另一个函数访问变量的唯一方法是编写代码使其不访问。 C++ 语言本身(或标准库)没有任何方法来阻止变量访问,除了使变量一开始就不可访问(
private成员访问、局部变量或类似的语言结构)。 -
"std::mutex 用于锁定相同代码块"。不,不是。互斥体不关心它是否是同一个块。
-
考虑将名称
run()更改为start()。代码中的注释说,“一些代码来启动这个设备。”如果这就是你描述它的作用,那么名称应该是“start()”。
标签: c++ multithreading c++11