1

The following code runs a simple background process repeatedly until requested to stop by the main thread:

#include <iostream>
#include <thread>
#include <chrono>

void sleep(int duration) {
        std::this_thread::sleep_for(std::chrono::milliseconds{duration});
}

void background(volatile bool *flag) {
    while(*flag) {
        std::cout << '*' << std::flush;
        sleep(500);
    }
}

int main() {
    bool flag=true;
    auto func = [&flag](){ background(&flag); };
    std::thread t{func};
    std::cin.ignore();
    flag=false;
    t.join();
}

However, the program seems to work just as well if background is defined without the volatile, i.e. void background(bool *flag).

So: 1) is this a correct use of volatile? and 2) is the volatile actually needed here?

Joe
  • 7,378
  • 4
  • 37
  • 54
Sir Visto
  • 683
  • 1
  • 4
  • 9

0 Answers0