原子操作是同时只能有一个线程执行一个操作,不用使用互斥量即可实现,但是速度慢,而且一般只支持原生的类型,不够灵活。更多的用处是作为信号量进行使用。
示例代码,以int
为例子:
#include <atomic>
#include <thread>
#include <iostream>
#include <cstdlib>
#include <vector>
int cnt = 0;
std::atomic_int cnt_ato = 0;
void thread_write_add(int n) {
for (int i = 0; i < n; ++i) {
cnt++;
}
}
void thread_write_add_atomic(int n) {
for (int i = 0; i < n; ++i) {
cnt_ato++;
}
}
int main() {
std::vector<std::thread>threads;
for (int i = 0; i < 10; ++i) {
threads.emplace_back(std::thread(&thread_write_add, 500000));
}
for (auto& t : threads) {
t.join();
}
threads.clear();
std::cout << "cnt = " << cnt << std::endl;
for (int i = 0; i < 10; ++i) {
threads.emplace_back(std::thread(&thread_write_add_atomic, 500000));
}
for (auto& t : threads) {
t.join();
}
threads.clear();
std::cout << "cnt_ato = " << cnt_ato << std::endl;
system("pause");
return 0;
}
输出结果:
使用原子操作的,保持了数据的正确性。