c++11 多线程编程--原子

以下是我关于c++11多线程编程的学习体会,希望大家多指正

目的: 1 原子类型的引入意味着不需要额外的同步机制就可以执行并发的读写操作。
            2 原子操作的确可以作为解决共享数据引起的问题的一种有效的手段。
示例:(代码已在VS2015 编译通过)
// test_atomic_1.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"
#include<atomic>
#include <thread>
#include<vector>
#include <iostream>
void fun(std::atomic_int &total)
{
 for (size_t i = 0; i < 1000; i++)
 {
  ++total;
 }
}
int main()
{
   std::atomic_int total(12);
   std::atomic_int total2 = 0;
   total2._My_val = 3;
   total2.store(13);
   int total1 = total2.load();;
   std::atomic_int total(12);
   int total1 = 12;
   std::vector<std::thread> threads;
   for (size_t i = 0; i < 10; i++)
   {
     threads.push_back(std::thread{ fun,std::ref(total) });
   }
   for (auto&tan : threads)
   {
    tan.join();
   }
    std::cout << "Result=" << total << std::endl;
    return 0;
}


多次运行程序得到的结果的都是 Result = 1002;
通过示例可以得出结论:在针对简单的数据类型需要共享的 ,使用原子类型可以在不显示的添加任何锁的情况下,避免死锁和竞争条件->防止多个线程同时访问一块共享区域。

原子操作:
    total2._My_val = 3;
    total2.store(13);  //设置原子的value为13
   int total1 = total2.load();//获取原子的value
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值