日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

std::atomic和std::mutex区别

發布時間:2025/3/12 编程问答 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 std::atomic和std::mutex区别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?std::atomic介紹?

?模板類std::atomic是C++11提供的原子操作類型,頭文件 #include<atomic>。?在多線程調用下,利用std::atomic可實現數據結構的無鎖設計。??

?和互斥量的不同之處在于,std::atomic原子操作,主要是保護一個變量,互斥量的保護范圍更大,可以一段代碼或一個變量。std::atomic?確保任意時刻只有一個線程對這個資源進行訪問,避免了鎖的使用,提高了效率。??

??原子類型和內置類型對照表如下:??

?

以下以兩個簡單的例子,比較std::mutex和std::atomic執行效率

atomic和mutex性能比較

使用std::mutex

#include "stdafx.h"#include <iostream> #include <ctime> #include <mutex> #include <thread> #include<future>std::mutex mtx;int cnt = 0; void mythread() {for (int i = 0; i < 1000000; i++){std::unique_lock<std::mutex> lock(mtx);cnt++;} }int main() {clock_t start_time = clock();std::thread t1(mythread);std::thread t2(mythread);t1.join();t2.join();clock_t cost_time = clock() - start_time;std::cout << "cnt= " << cnt << " 耗時:" << cost_time << "ms" << std::endl;return 0; }

執行結果:

使用std::atomic

#include <iostream> #include <ctime> #include <thread> #include<future>std::atomic<int> cnt(0);void mythread() {for (int i = 0; i < 1000000; i++){cnt++;} }int main() {clock_t start_time = clock();std::thread t1(mythread);std::thread t2(mythread);t1.join();t2.join();clock_t cost_time = clock() - start_time;std::cout << "cnt= " << cnt << " 耗時:" << cost_time << "ms" << std::endl;return 0; }

執行結果如下:

總結

?通過以上比較,可以看出來,使用std::atomic,耗時比std::mutex低非常多,?使用 std::atomic???能大大的提高程序的運行效率。??

總結

以上是生活随笔為你收集整理的std::atomic和std::mutex区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。