linux下mutex與atomic效能比較

來源:互聯網
上載者:User

標籤:

一種是用boost::atomic;一種直接加鎖;代碼很簡單:

#include <boost/atomic/atomic.hpp>#include <iostream>#include <stdlib.h>#include <boost/thread/mutex.hpp>#include <pthread.h>#include <stdio.h> #include <sys/time.h> #include <time.h> static int loop_num = 10000;boost::atomic<int> a(0);static boost::mutex mtx_;static void* test_atomic(void* agr){int num = *(int*)agr;struct timeval t_start,t_end; long cost_time = 0; gettimeofday(&t_start, NULL); long start = ((long)t_start.tv_sec)*1000+(long)t_start.tv_usec/1000; while (num--){++a;}gettimeofday(&t_end, NULL); long end = ((long)t_end.tv_sec)*1000+(long)t_end.tv_usec/1000; cost_time = end - start; std::cout << "loopnum:" << loop_num << " test_atomic cost "<< cost_time << " ms\n";return NULL;}static int b = 0;static void* test_lock(void* agr){int num = *(int*)agr;struct timeval t_start,t_end; long cost_time = 0; gettimeofday(&t_start, NULL); long start = ((long)t_start.tv_sec)*1000+(long)t_start.tv_usec/1000; while(num--){{boost::mutex::scoped_lock lock(mtx_);++b;}}gettimeofday(&t_end, NULL); long end = ((long)t_end.tv_sec)*1000+(long)t_end.tv_usec/1000; cost_time = end - start; std::cout  << "loopnum:" << loop_num << "test_lock cost "<< cost_time << " ms\n";return NULL;}int main(int agrc, char** argv){if (agrc < 2){std::cout << "please input num:" << std::endl;return 0;}pthread_t main_tid;int num1 = atoi((char*)argv[1]);int num2 = atoi((char*)argv[2]);if (num1 == 0){pthread_create(&main_tid, NULL, &test_atomic, &num2); //建立線程    pthread_join(main_tid, NULL);}else{pthread_create(&main_tid, NULL, &test_lock, &num2); //建立線程    pthread_join(main_tid, NULL);}}
測試結果如下:

[email protected]:~/code$ ./test 0 1000
loopnum:10000 test_atomic cost 0 ms
[email protected]:~/code$ ./test 1 1000
loopnum:10000test_lock cost 0 ms
[email protected]:~/code$ ./test 1 100000
loopnum:10000test_lock cost 9 ms
[email protected]:~/code$ ./test 0 100000
loopnum:10000 test_atomic cost 2 ms

隨著loop數目的增大差距越來越大;與兩者實現有關,一種是臨界區阻塞,一種用了compare change技術,甚至看內部實現用了彙編。

在我的筆記本結果是這樣,也說明了問題。

linux下mutex與atomic效能比較

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.