mercredi 18 septembre 2019

How do I prevent another thread to modify a state flag?

I have a class

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*/
    }
}

In the doMaintenance() function, the flag would be changed by other threads after the (flag==eRunning) checking. How do I gracefully prevent this happen?

Aucun commentaire:

Enregistrer un commentaire