Question

My question relates to using volatile for stop flag in order to stop method of some threaded server. In some open-source projects I see declaring stop as volatile:

class ThreadedServer {
public:
    //...
    // this method will be launched in separate worker thread
    void run() {
        while (!stop_) {
            //some useful work...
        }
        if (stop_) {
            //cleanup
        }
    }
    void stop() {
        stop_ = true;
    }
private:
    volatile bool stop_;
};

In my server I declared a stop field WITHOUT volatile modifier, and everything works. So why to make class variable volatile in such concrete situation?

Was it helpful?

Solution

volatile signals that the value of stop_ has to be read from the main memory every time it is evaluated. What could happen if you didn't do that, in the worst case, is to run without stopping, because thread1 sets stop_ to false, but thread2 does only look at his buffered stop on the CPU cache.

But keep in mind that it must not result in a problem, but it could.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top