以下代码重复运行一个简单的后台进程,直到主线程请求停止:
#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();
}
然而,如果没有volatile的背景定义,即void background(bool *flag)
,该程序似乎也能正常工作。
所以:1)这是正确使用volatile吗? 2)这里实际需要的是挥发性的吗?