摘要:本文主要向大家介绍了C++语言11之atomic原子操作,通过具体的内容向大家展示,希望对大家学习C++语言有所帮助。
本文主要向大家介绍了C++语言11之atomic原子操作,通过具体的内容向大家展示,希望对大家学习C++语言有所帮助。
· atomic介绍
atomic对int、char、bool等数据结构进行了原子性封装,在多线程环境中,对std::atomic对象的访问不会造成竞争-冒险。利用std::atomic可实现数据结构的无锁设计。
所谓的原子操作,取的就是“原子是最小的、不可分割的最小个体”的意义,它表示在多个线程访问同一个全局资源的时候,能够确保所有其他的线程都不在同一时间内访问相同的资源。也就是他确保了在同一时刻只有唯一的线程对这个资源进行访问。这有点类似互斥对象对共享资源的访问的保护,但是原子操作更加接近底层,因而效率更高。
在以往的C++标准中并没有对原子操作进行规定,我们往往是使用汇编语言,或者是借助第三方的线程库,例如intel的pthread来实现。在新标准C++11,引入了原子操作的概念,并通过这个新的头文件提供了多种原子操作数据类型,例如,atomic_bool,atomic_int等等,如果我们在多个线程中对这些类型的共享资源进行操作,编译器将保证这些操作都是原子性的,也就是说,确保任意时刻只有一个线程对这个资源进行访问,编译器将保证,多个线程访问这个共享资源的正确性。从而避免了锁的使用,提高了效率。
· atomic高效体现
加锁不使用atomic:
[cpp] view plain copy
1. #include
2. #include
3. #include
4. #include
5. #include
6.
7. std::mutex mtx;
8. size_t count = 0;
9.
10. void threadFun()
11. {
12. for (int i = 0; i < 10000; i++)
13. {
14. // 防止多个线程同时访问同一资源
15. std::unique_lock
16. count++;
17. }
18. }
19.
20. int main(void)
21. {
22. clock_t start_time = clock();
23.
24. // 启动多个线程
25. std::vector
26. for (int i = 0; i < 10; i++)
27. threads.push_back(std::thread(threadFun));
28. for (auto&thad : threads)
29. thad.join();
30.
31. // 检测count是否正确 10000*10 = 100000
32. std::cout << "count number:" << count << std::endl;
33.
34. clock_t end_time = clock();
35. std::cout << "耗时:" << end_time - start_time << "ms" << std::endl;
36.
37. return 0;
38. }
使用atomic:
[cpp] view plain copy
1. #include
2. #include
3. #include
4. #include
5. #include
6.
7.
8. std::atomic
9.
10. void threadFun()
11. {
12. for (int i = 0; i < 10000; i++)
13. count++;
14. }
15.
16. int main(void)
17. {
18. clock_t start_time = clock();
19.
20. // 启动多个线程
21. std::vector
22. for (int i = 0; i < 10; i++)
23. threads.push_back(std::thread(threadFun));
24. for (auto&thad : threads)
25. thad.join();
26.
27. // 检测count是否正确 10000*10 = 100000
28. std::cout << "count number:" << count << std::endl;
29.
30. clock_t end_time = clock();
31. std::cout << "耗时:" << end_time - start_time << "ms" << std::endl;
32.
33. return 0;
34. }
本文由职坐标整理并发布,了解更多内容,请关注职坐标编程语言C/C+频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号