【C++11多线程】线程同步之线程互斥:atomic

1.引例

#include <iostream>
#include <thread>

int my_count{ 0 }; // 定义一个全局变量

void my_thread() // 线程入口函数
{
    for (int i = 0; i < 1000000; i++)
    {
        my_count++;
    }
    return;
}

int main()
{
    std::thread td1(my_thread);
    std::thread td2(my_thread);

    td1.join();
    td2.join();

    std::cout << "两个线程执行完毕,最终my_count的值是" << my_count << std::endl;

    return 0;
}

在这里插入图片描述

2.使用互斥量std::mutex解决

#include <iostream>
#include <thread>
#include <mutex>

int my_count{ 0 }; // 定义一个全局变量

std::mutex my_mutex;

void my_thread() // 线程入口函数
{
    for (int i = 0; i < 1000000; i++)
    {
        my_mutex.lock();
        my_count++;
        my_mutex.unlock();
    }
    return;
}

int main()
{
    std::thread td1(my_thread);
    std::thread td2(my_thread);

    td1.join();
    td2.join();

    std::cout << "两个线程执行完毕,最终my_count的值是" << my_count << std::endl;

    return 0;
}

在这里插入图片描述

3.使用原子操作std::atomic解决

原子操作是指“不可分割的操作”,即在多线程中不会被打断的程序执行片段,也就是说,这种操作状态要么是完成的,要么是没完成的,不可能出现半完成状态。

std::atomic 是个类模板,其构造函数如下,更详细的解释:https://cplusplus.com/reference/atomic/

在这里插入图片描述

std::atomic<int> my_count = 0; 等价于 std::atomic_int my_count = 0;,原因如下:

在这里插入图片描述

互斥量std::mutex一般针对的是一个代码段,而原子操作std::atomic一般针对的是一个变量。与互斥量std::mutex相比,原子操作std::atomic的效率更胜一筹。

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> my_count(0);

void my_thread() // 线程入口函数
{
    for (int i = 0; i < 1000000; i++)
    {
        my_count++; // 原子操作不会被打断
        //my_count += 1; // 结果正确
        //my_count = my_count + 1; // 结果错误
    }
    return;
}

int main()
{
    std::thread td1(my_thread);
    std::thread td2(my_thread);

    td1.join();
    td2.join();

    std::cout << "两个线程执行完毕,最终my_count的值是" << my_count << std::endl;

    return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值