【问题标题】:How do I prevent another thread to modify a state flag?如何防止另一个线程修改状态标志?
【发布时间】: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


【解决方案1】:

还有其他问题需要解决。例如,假设设备处于停止状态。然后,在两个线程中执行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*/
    }
}

【讨论】:

  • 谢谢大家,包括 cmets 中的人。另外,我昨天在 doMaintenance() 中尝试了 run() 和 start() 中的 lock_guard 和 m_mutex.try_lock() 。因为我不希望 doMaintenance 等待,所以在它被锁定时返回。它运作良好。但我想知道是否有一个 std::try_lock() 来代替 mutex::try_lock()。我发现有 std::try_lock()。但它需要2个参数。我不知道为什么。 lock_guard 和 scoped_lock 有什么区别?
猜你喜欢
  • 2015-02-18
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 2012-05-11
  • 1970-01-01
  • 2019-04-02
相关资源
最近更新 更多