C++之原子操作(atomic)

原子操作

所谓原子操作是指不会被线程调度机制打断的操作;这种操作一旦开始,就一直运行到结束,中间不会有任何 context switch(切换到另一个线程)。原子操作是不可分割的,在执行完毕之前不会被任何其它任务或事件中断。

下面看一个例子

#include<iostream>
#include<thread>
#include<atomic>
#include<time.h>
#include<mutex>
using namespace std;


mutex mtx;    //定义互斥锁
#define MAX 2000000
#define THREAD_COUNT 10
//atomic_int total(0);
int total = 0;
void thread_task()
{
    for (int i = 0; i < MAX; i++)
    {
        //mtx.lock();
        total += 1;
        total -= 1;
        //mtx.unlock();
    }
}
int main()
{
    clock_t start = clock();
    thread t[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; ++i)
    {
        t[i] = thread(thread_task);
    }
    for (int i = 0; i < THREAD_COUNT; ++i)
    {
        t[i].join();
    }
    clock_t finish = clock();
    cout << "result:" << total << endl;
    cout << "time:" << finish - start << endl;
    return 0;
}

这是一个程序,创建10个线程,在函数中将0加一再减一重复2000000次,最终得到的结果应该还是0,我们运行结果如下

为什么呢???我们不难想到是线程同步问题。我们尝试给函数的操作加锁。

#include<iostream>
#include<thread>
#include<atomic>
#include<time.h>
#include<mutex>
using namespace std;


mutex mtx;    //定义互斥锁
#define MAX 2000000
#define THREAD_COUNT 10
//atomic_int total(0);
int total = 0;
void thread_task()
{
    for (int i = 0; i < MAX; i++)
    {
        mtx.lock();
        total += 1;
        total -= 1;
        mtx.unlock();
    }
}
int main()
{
    clock_t start = clock();
    thread t[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; ++i)
    {
        t[i] = thread(thread_task);
    }
    for (int i = 0; i < THREAD_COUNT; ++i)
    {
        t[i].join();
    }
    clock_t finish = clock();
    cout << "result:" << total << endl;
    cout << "time:" << finish - start << endl;
    return 0;
}

此时答案正确但是效率显著降低,这也是情理之中的。

这时候引入原子操作

#include<iostream>
#include<thread>
#include<atomic>
#include<time.h>
#include<mutex>
using namespace std;

mutex mtx;    //定义互斥锁
#define MAX 2000000
#define THREAD_COUNT 10
atomic_int total(0);
//int total = 0;
void thread_task()
{
    for (int i = 0; i < MAX; i++)
    {
        //mtx.lock();
        total += 1;
        total -= 1;
        //mtx.unlock();
    }
}
int main()
{
    clock_t start = clock();
    thread t[THREAD_COUNT];
    for (int i = 0; i < THREAD_COUNT; ++i)
    {
        t[i] = thread(thread_task);
    }
    for (int i = 0; i < THREAD_COUNT; ++i)
    {
        t[i].join();
    }
    clock_t finish = clock();
    cout << "result:" << total << endl;
    cout << "time:" << finish - start << endl;
    return 0;
}

此时可见性能得到了大幅优化。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小谢%同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值