c++ - 如何防止另一个线程修改状态标志?
问题描述
我有一堂课
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)
。我如何优雅地防止这种情况发生?
解决方案
还有其他问题需要解决。例如,假设设备处于停止状态。然后,在两个线程中,您执行run()
. 然后两个线程开始执行相同的启动顺序。我们也应该注意这一点。
因此,最简单的解决方案是不允许任何run()
,stop()
和doMaintenance()
同时运行。这可以通过互斥锁轻松解决:
class Device
{
enum State {eStopped, eRunning}
State flag = eStopped;
std::mutex m_mutex;
public:
void run(){
std::scoped_lock lock(m_mutex);
if(flag==eRunning){return;}
/*some codes to start this device*/
flag = eRunning;
}
void stop(){
std::scoped_lock lock(m_mutex);
if(flag==eStopped){return;}
/*some codes to stop this device*/
flag = eStopped;
}
void doMaintenance(){
std::scoped_lock lock(m_mutex);
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*/
}
}
推荐阅读
- python-3.x - 为什么我在 Jupyter 中使用 TensorFlow 时遇到问题?
- python - TensorFlow-serving 找不到元图 Def
- r - 如何在 ggplot2 中定义 bin?
- java - 如何将支票转换为包含小数位的单词
- java - 服务(事件总线订阅者)未收到来自 Activity 的帖子
- android - onStop() 或 super.onStop() 返回后 Activity 是否可终止
- r - 如何在 R 中编写一个 RegEx 函数来选择具有字母 e 但没有字符串 ee 的国家/地区
- mongodb - Mongoose 模块中 collection.js 中未定义的 Mongoose TypeError '无法读取命名空间'
- java - 不能在 JavaFX 中使用从 ParametreController 传递到 GameController 的初始化(GameController)方法中的对象
- python - Python:在数据框的多列上使用函数