c++举一个原子类型是bool的操作例子
以下是一个使用原子类型为bool的操作例子:
#include <iostream>
#include <atomic>
#include <thread>
std::atomic<bool> flag(false); // 原子类型的bool变量
void worker()
{
while (!flag.load()) // 加载原子变量的值
{
// 执行一些操作
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
std::cout << "Worker thread exiting..." << std::endl;
}
int main()
{
std::thread t(worker);
std::cout << "Press ENTER to stop the worker thread." << std::endl;
std::cin.get();
flag.store(true); // 存储原子变量的值
t.join();
return 0;
}
在上面的例子中,我们创建了一个原子类型为bool的变量flag,并在工作线程中使用了这个变量。工作线程会不断地检查flag的值,直到它被设置为true时才停止执行。在主线程中,我们等待用户按下回车键后,将flag的值设置为true,从而触发工作线程的退出。
在多线程中,原子类型的操作能够确保对变量的操作是原子的,避免了竞态条件和数据竞争问题。
原文地址: https://www.cveoy.top/t/topic/i8IJ 著作权归作者所有。请勿转载和采集!