类模板
template <class T> struct atomic;
多线程小结:
- 非原子操作,不加锁,效率很高,但无法得到正确的结果
- 非原子操作,加锁,效率很低,但结果正确
- 原子操作,效率很高,且结果正确
- 原子操作是指不会被线程调度机制打断的操作。这种操作一旦开始,就一直运行到结束,中间不会有任何任何上下文切换。
- 原子操作可以是一个步骤,也可以是多个操作步骤,但其顺序不可被打乱,也不可以被切合只执行其中一部分。
- 将整个操作视作一个整体是原子操作的核心特征。
n++;//这条指令不是原子操作
编程实验
- 非原子操作,不加锁,效率很高,但无法得到正确的结果
- 非原子操作,加锁,效率很低,但结果正确
- 原子操作,效率很高,且结果正确
测试1:非原子操作,无锁
#include <iostream>
#include <thread>
using namespace::std;
int g_sum = 0;
void add()
{
for (uint32_t i=0; i<10000000; ++i)
++g_sum;
}
int main()
{
auto beginTime = clock();
thread t1(add);
thread t2(add);
t1.join();
t2.join();
auto endTime = clock();
cout << "time consuming : " << endTime - beginTime << endl;
cout << "calculated value: " << g_sum << endl;
return 0;
}
输出:[速度快,结果错误]
time consuming : 47
calculated value: 10856025
测试2:非原子操作,有锁
#include <iostream>
#include <thread>
#include <mutex>
using namespace::std;
int g_sum = 0;
mutex g_mutex;
void add()
{
for (uint32_t i=0; i<10000000; ++i)
{
g_mutex.lock();
++g_sum;
g_mutex.unlock();
}
}
int main()
{
auto beginTime = clock();
thread t1(add);
thread t2(add);
t1.join();
t2.join();
auto endTime = clock();
cout << "time consuming : " << endTime - beginTime << endl;
cout << "calculated value: " << g_sum << endl;
return 0;
}
输出:[结果正确,速度慢]
time consuming : 571
calculated value: 20000000
测试3:原子操作 atomic<int> g_sum {0};
#include <iostream>
#include <thread>
#include <atomic>
using namespace::std;
atomic<int> g_sum {0};
void add()
{
for (uint32_t i=0; i<10000000; ++i)
{
++g_sum;
}
}
int main()
{
auto beginTime = clock();
thread t1(add);
thread t2(add);
t1.join();
t2.join();
auto endTime = clock();
cout << "time consuming : " << endTime - beginTime << endl;
cout << "calculated value: " << g_sum << endl;
return 0;
}
输出:[速度快,结果正确]
time consuming : 292
calculated value: 20000000
一般用法
- 用于多线程环境中的访问标记
- 用于多线程环境中的访问统计
#include <iostream>
#include <thread>
#include <atomic>
using namespace::std;
atomic<bool> g_ifEnd {false};
void mythread()
{
cout << "mythread begin" << endl;
chrono::microseconds dura(1000);
while (!g_ifEnd)
{
cout << "mythread thread id :" << this_thread::get_id() << endl;
this_thread::sleep_for(dura);
}
cout << "mythread begin" << endl;
}
int main()
{
cout << "main end" << endl;
thread t1(mythread);
this_thread::sleep_for(chrono::microseconds(5000));
g_ifEnd = true;
t1.join();
cout << "main end" << endl;
return 0;
}
输出:
main end
mythread begin
mythread thread id :2
mythread begin
main end
【C++并发与多线程】 10_shared_future、automic - C_经典C_数据结构_现代C_现代C_多线程_C_内存管理_Linux网络编程 - SegmentFault 思否
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)