以下是我关于c++11多线程编程的学习体会,希望大家多指正
目的: 1 原子类型的引入意味着不需要额外的同步机制就可以执行并发的读写操作。
2 原子操作的确可以作为解决共享数据引起的问题的一种有效的手段。
示例:(代码已在VS2015 编译通过)
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
total2._My_val = 3;
total2.store(13); //设置原子的value为13
int total1 = total2.load();//获取原子的value