C++11 原子变量示例:多线程计数器
一个使用原子变量的例子是多线程计数器。在下面的示例中,我们将使用一个原子变量来实现一个简单的计数器,多个线程可以同时对其进行递增操作。
#include <iostream>
#include <thread>
#include <atomic>
std::atomic<int> counter(0);
void incrementCounter() {
for (int i = 0; i < 1000; ++i) {
counter++;
}
}
int main() {
std::thread thread1(incrementCounter);
std::thread thread2(incrementCounter);
thread1.join();
thread2.join();
std::cout << 'Counter value: ' << counter << std::endl;
return 0;
}
在上面的示例中,我们创建了一个原子变量counter,并将其初始值设置为0。然后,我们创建了两个线程thread1和thread2,每个线程都会对counter进行1000次递增操作。最后,我们在主线程中输出counter的值。
由于原子变量的特性,多个线程可以同时对其进行读写操作,而不会引发数据竞争。这样,我们可以确保计数器的值是正确的,而不需要使用互斥锁等同步机制。
原文地址: https://www.cveoy.top/t/topic/lK9d 著作权归作者所有。请勿转载和采集!