一种是用boost::atomic;一种直接加锁;代码很简单:

[cpp]  view plain copy linux下mutex与atomic性能比较_创建线程 linux下mutex与atomic性能比较_加锁_02
  1. #include <boost/atomic/atomic.hpp>  
  2. #include <iostream>  
  3. #include <stdlib.h>  
  4. #include <boost/thread/mutex.hpp>  
  5. #include <pthread.h>  
  6. #include <stdio.h>   
  7. #include <sys/time.h>   
  8. #include <time.h>   
  9.   
  10. static int loop_num = 10000;  
  11. boost::atomic<int> a(0);  
  12. static boost::mutex mtx_;  
  13. static void* test_atomic(void* agr){  
  14.     int num = *(int*)agr;  
  15.     struct timeval t_start,t_end;   
  16.   
  17.     long cost_time = 0;   
  18.     gettimeofday(&t_start, NULL);   
  19.     long start = ((long)t_start.tv_sec)*1000+(long)t_start.tv_usec/1000;   
  20.   
  21.     while (num--){  
  22.         ++a;  
  23.     }  
  24.   
  25.     gettimeofday(&t_end, NULL);   
  26.     long end = ((long)t_end.tv_sec)*1000+(long)t_end.tv_usec/1000;   
  27.     cost_time = end - start;   
  28.     std::cout << "loopnum:" << loop_num << " test_atomic cost "<< cost_time << " ms\n";  
  29.     return NULL;  
  30. }  
  31.   
  32. static int b = 0;  
  33. static void* test_lock(void* agr){  
  34.     int num = *(int*)agr;  
  35.   
  36.     struct timeval t_start,t_end;   
  37.   
  38.     long cost_time = 0;   
  39.     gettimeofday(&t_start, NULL);   
  40.     long start = ((long)t_start.tv_sec)*1000+(long)t_start.tv_usec/1000;   
  41.   
  42.     while(num--){  
  43.         {  
  44.             boost::mutex::scoped_lock lock(mtx_);  
  45.             ++b;  
  46.         }  
  47.     }  
  48.     gettimeofday(&t_end, NULL);   
  49.     long end = ((long)t_end.tv_sec)*1000+(long)t_end.tv_usec/1000;   
  50.     cost_time = end - start;   
  51.     std::cout  << "loopnum:" << loop_num << "test_lock cost "<< cost_time << " ms\n";  
  52.     return NULL;  
  53. }  
  54. int main(int agrc, char** argv){  
  55.     if (agrc < 2){  
  56.         std::cout << "please input num:" << std::endl;  
  57.         return 0;  
  58.     }  
  59.     pthread_t main_tid;  
  60.     int num1 = atoi((char*)argv[1]);  
  61.     int num2 = atoi((char*)argv[2]);  
  62.     if (num1 == 0){  
  63.         pthread_create(&main_tid, NULL, &test_atomic, &num2); //创建线程  
  64.             pthread_join(main_tid, NULL);  
  65.     }  
  66.     else{  
  67.         pthread_create(&main_tid, NULL, &test_lock, &num2); //创建线程  
  68.             pthread_join(main_tid, NULL);  
  69.     }  
  70. }  
测试结果如下:

allen@allen-ThinkPad-Edge-E431:~/code$ ./test 0 1000
loopnum:10000 test_atomic cost 0 ms
allen@allen-ThinkPad-Edge-E431:~/code$ ./test 1 1000
loopnum:10000test_lock cost 0 ms
allen@allen-ThinkPad-Edge-E431:~/code$ ./test 1 100000
loopnum:10000test_lock cost 9 ms
allen@allen-ThinkPad-Edge-E431:~/code$ ./test 0 100000
loopnum:10000 test_atomic cost 2 ms

随着loop数目的增大差距越来越大;与两者实现有关,一种是临界区阻塞,一种用了compare change技术,甚至看内部实现用了汇编。

在我的笔记本结果是这样,也说明了问题。