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

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

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

输出结果:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值