C++11多线程的原子操作

版权声明:所有的博客都是个人笔记,交流可以留言或者加QQ:2630492017 https://blog.csdn.net/qq_35976351/article/details/85015020

原子操作是同时只能有一个线程执行一个操作,不用使用互斥量即可实现,但是速度慢,而且一般只支持原生的类型,不够灵活。更多的用处是作为信号量进行使用。

示例代码,以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;
}

输出结果:

使用原子操作的,保持了数据的正确性。

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/85015020