无锁编程实战演练

来源:互联网 发布:淘宝童装店铺招牌图片 编辑:程序博客网 时间:2024/05/23 23:02

前段时间研究过一阵子无锁化编程。刚写了几个简单的程序,来验证了下自己学到的一些概念。

测试场景:假设有一个应用:现在有一个全局变量,用来计数,再创建10个线程并发执行,每个线程中循环对这个全局变量进行++操作(i++),循环加2000000次。

所以很容易知道,这必然会涉及到并发互斥操作。下面通过三种方式来实现这种并发操作。并对比出其在效率上的不同之处。

这里先贴上代码,共5个文件:2个用于做时间统计的文件:timer.h  timer.cpp。这两个文件是临时封装的,只用来计时,可以不必细看。

 timer.h

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #ifndef TIMER_H  
  2. #define TIMER_H  
  3.   
  4. #include <sys/time.h>  
  5. class Timer  
  6. {  
  7. public:   
  8.     Timer();  
  9.     // 开始计时时间  
  10.     void Start();  
  11.     // 终止计时时间  
  12.     void Stop();  
  13.     // 重新设定  
  14.     void Reset();  
  15.     // 耗时时间  
  16.     void Cost_time();  
  17. private:  
  18.     struct timeval t1;  
  19.     struct timeval t2;  
  20.     bool b1,b2;  
  21. };  
  22. #endif  


timer.cpp

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include "timer.h"  
  2. #include <stdio.h>  
  3.   
  4. Timer::Timer()  
  5. {  
  6.     b1 = false;  
  7.     b2 = false;  
  8. }  
  9. void Timer::Start()  
  10. {  
  11.     gettimeofday(&t1,NULL);    
  12.     b1 = true;  
  13.     b2 = false;  
  14. }  
  15.   
  16. void Timer::Stop()  
  17. {     
  18.     if (b1 == true)  
  19.     {  
  20.         gettimeofday(&t2,NULL);    
  21.         b2 = true;  
  22.     }  
  23. }  
  24.   
  25. void Timer::Reset()  
  26. {     
  27.     b1 = false;  
  28.     b2 = false;  
  29. }  
  30.   
  31. void Timer::Cost_time()  
  32. {  
  33.     if (b1 == false)  
  34.     {  
  35.         printf("计时出错,应该先执行Start(),然后执行Stop(),再来执行Cost_time()");  
  36.         return ;  
  37.     }  
  38.     else if (b2 == false)  
  39.     {  
  40.         printf("计时出错,应该执行完Stop(),再来执行Cost_time()");  
  41.         return ;  
  42.     }  
  43.     else  
  44.     {  
  45.         int usec,sec;  
  46.         bool borrow = false;  
  47.         if (t2.tv_usec > t1.tv_usec)  
  48.         {  
  49.             usec = t2.tv_usec - t1.tv_usec;  
  50.         }  
  51.         else  
  52.         {  
  53.             borrow = true;  
  54.             usec = t2.tv_usec+1000000 - t1.tv_usec;  
  55.         }  
  56.   
  57.         if (borrow)  
  58.         {  
  59.             sec = t2.tv_sec-1 - t1.tv_sec;  
  60.         }  
  61.         else  
  62.         {  
  63.             sec = t2.tv_sec - t1.tv_sec;  
  64.         }  
  65.         printf("花费时间:%d秒 %d微秒\n",sec,usec);  
  66.     }  
  67. }  


传统互斥量加锁方式 lock.cpp

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <pthread.h>  
  4. #include <time.h>  
  5. #include "timer.h"  
  6.   
  7. pthread_mutex_t mutex_lock;  
  8. static volatile int count = 0;  
  9. void *test_func(void *arg)  
  10. {  
  11.         int i = 0;  
  12.         for(i = 0; i < 2000000; i++)  
  13.         {  
  14.                 pthread_mutex_lock(&mutex_lock);  
  15.                 count++;  
  16.                 pthread_mutex_unlock(&mutex_lock);  
  17.         }  
  18.         return NULL;  
  19. }  
  20.   
  21. int main(int argc, const char *argv[])  
  22. {  
  23.     Timer timer; // 为了计时,临时封装的一个类Timer。  
  24.     timer.Start();  // 计时开始  
  25.     pthread_mutex_init(&mutex_lock, NULL);  
  26.     pthread_t thread_ids[10];  
  27.     int i = 0;  
  28.     for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++)  
  29.     {  
  30.         pthread_create(&thread_ids[i], NULL, test_func, NULL);  
  31.     }  
  32.   
  33.     for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++)  
  34.     {  
  35.         pthread_join(thread_ids[i], NULL);  
  36.     }  
  37.   
  38.     timer.Stop();// 计时结束  
  39.     timer.Cost_time();// 打印花费时间  
  40.     printf("结果:count = %d\n",count);  
  41.   
  42.     return 0;  
  43. }  


no lock 不加锁的形式 nolock.cpp

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <pthread.h>  
  4. #include <unistd.h>  
  5. #include <time.h>  
  6. #include "timer.h"  
  7.   
  8. int mutex = 0;  
  9. int lock = 0;  
  10. int unlock = 1;  
  11.   
  12. static volatile int count = 0;  
  13. void *test_func(void *arg)  
  14. {  
  15.         int i = 0;  
  16.         for(i = 0; i < 2000000; i++)  
  17.     {  
  18.         while (!(__sync_bool_compare_and_swap (&mutex,lock, 1) ))usleep(100000);  
  19.          count++;  
  20.          __sync_bool_compare_and_swap (&mutex, unlock, 0);  
  21.         }  
  22.         return NULL;  
  23. }  
  24.   
  25. int main(int argc, const char *argv[])  
  26. {  
  27.     Timer timer;  
  28.     timer.Start();  
  29.     pthread_t thread_ids[10];  
  30.     int i = 0;  
  31.   
  32.     for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++)  
  33.     {  
  34.             pthread_create(&thread_ids[i], NULL, test_func, NULL);  
  35.     }  
  36.   
  37.     for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++)  
  38.     {  
  39.             pthread_join(thread_ids[i], NULL);  
  40.     }  
  41.   
  42.     timer.Stop();  
  43.     timer.Cost_time();  
  44.     printf("结果:count = %d\n",count);  
  45.   
  46.     return 0;  
  47. }  


原子函数进行统计方式 atomic.cpp

[html] view plaincopy在CODE上查看代码片派生到我的代码片
  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <pthread.h>  
  4. #include <unistd.h>  
  5. #include <time.h>  
  6. #include "timer.h"  
  7.   
  8. static volatile int count = 0;  
  9. void *test_func(void *arg)  
  10. {  
  11.         int i = 0;  
  12.         for(i = 0; i < 2000000; i++)  
  13.         {  
  14.             __sync_fetch_and_add(&count, 1);  
  15.         }  
  16.         return NULL;  
  17. }  
  18.   
  19. int main(int argc, const char *argv[])  
  20. {  
  21.     Timer timer;  
  22.     timer.Start();  
  23.     pthread_t thread_ids[10];  
  24.     int i = 0;  
  25.   
  26.     for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++){  
  27.             pthread_create(&thread_ids[i], NULL, test_func, NULL);  
  28.     }  
  29.   
  30.     for(i = 0; i < sizeof(thread_ids)/sizeof(pthread_t); i++){  
  31.             pthread_join(thread_ids[i], NULL);  
  32.     }  
  33.   
  34.     timer.Stop();  
  35.     timer.Cost_time();  
  36.     printf("结果:count = %d\n",count);  
  37.     return 0;  
  38. }  


#################################################################3

好,代码粘贴完毕。下面进入测试环节:

编译:

[adapter@ZHEJIANG test3]$ g++ lock.cpp ./timer.cpp  -lpthread -o lock ;
[adapter@ZHEJIANG test3]$ g++ nolock.cpp ./timer.cpp  -lpthread -o nolock ;
[adapter@ZHEJIANG test3]$  g++ atomic.cpp ./timer.cpp  -lpthread -o atomic ;

 

每一个线程循环加2000000次。
第一组测验
[adapter@ZHEJIANG test3]$ ./lock
花费时间:3秒 109807微秒
结果:count = 20000000
[adapter@ZHEJIANG test3]$ ./nolock
花费时间:7秒 595784微秒
结果:count = 20000000
[adapter@ZHEJIANG test3]$ ./atomic
花费时间:0秒 381022微秒
结果:count = 20000000

结论:
可以看出,原子操作函数的速度是最快的,其他两种方式根本就没法比。而无锁操作是在原子操作函数的基础上形成的。
为什么无锁操作的效率会这么低?如果效率低的话,那还有什么意义,为什么现在大家都提倡无锁编程呢?为什么?咱先不
解释,先用数据说话。

第二组测验:
原子操作代码不变,加锁操作代码不变。改动一下无锁操作的代码。
将如下代码更改
while (!(__sync_bool_compare_and_swap (&mutex,lock, 1) ));
更改后:while (!(__sync_bool_compare_and_swap (&mutex,lock, 1) )) usleep(1);
让他睡一微秒。
为什么要这样改代码?这样启不是会更慢?你的猜测是不无道理的,但是一个不休息的人干的活未必比有休息的人干的活多。

[adapter@ZHEJIANG test3]$ ./lock
花费时间:2秒 970773微秒
结果:count = 20000000
[adapter@ZHEJIANG test3]$ ./nolock
花费时间:0秒 685404微秒
结果:count = 20000000
[adapter@ZHEJIANG test3]$ ./atomic
花费时间:0秒 380675微秒
结果:count = 20000000

结论:
不用明说,大家看到的结果是不是很诧异?是不是!有木有!怎么会是这样。无锁加上usleep(1),睡一会,反而会变得这么快。
虽和原子操作相比次了一点,但已经甩开有锁同步好几条街了,无锁比有锁快是应该的,但为什么睡一会会更快,不睡就比有锁
还慢那么多呢?怎么回事。是不是这个测试的时候cpu出现了不稳定的事情。
那好,那再测试几次。
[adapter@ZHEJIANG test3]$ ./nolock
花费时间:0秒 684938微秒
结果:count = 20000000
[adapter@ZHEJIANG test3]$ ./nolock
花费时间:0秒 686039微秒
结果:count = 20000000
[adapter@ZHEJIANG test3]$ ./nolock
花费时间:0秒 685928微秒
结果:count = 20000000

现在总没话可说了,这是事实!但为什么,我也不会解释。

很好奇,为什么越休息,效率越高。电脑是机器,它可不是人。怎么会这样?
那我就让它多休息一会:
 while (!(__sync_bool_compare_and_swap (&mutex,lock, 1) ))usleep(10); //之前是1,现在改成10了。
 下面就再单独对比一个nolock无锁方式。
[adapter@ZHEJIANG test3]$ ./nolock //usleep(1);
花费时间:0秒 686039微秒
结果:count = 20000000
[adapter@ZHEJIANG test3]$ ./nolock //usleep(10);
花费时间:0秒 680307微秒
结果:count = 20000000
nolock,结果usleep(10)居然比uleep(1)还要快一点。

那么这样呢:
while (!(__sync_bool_compare_and_swap (&mutex,lock, 1) ))usleep(100); //之前是10,现在改成100了。
[adapter@ZHEJIANG test3]$ ./nolock //usleep(100)
花费时间:0秒 661935微秒
结果:count = 20000000
还是睡的越久,效率越高。

那我再试一下usleep(1000)
while (!(__sync_bool_compare_and_swap (&mutex,lock, 1) ))usleep(1000); //之前是100,现在改成1000了。
[adapter@ZHEJIANG test3]$ ./nolock // usleep(1000);
花费时间:0秒 652411微秒
结果:count = 20000000
还是睡的越久,效率越高。

那我再试一下usleep(10000)
while (!(__sync_bool_compare_and_swap (&mutex,lock, 1) ))usleep(10000); //之前是1000,现在改成10000了。
[adapter@ZHEJIANG test3]$ ./nolock
花费时间:0秒 626267微秒
结果:count = 20000000
还是睡的越久,效率越高。

那我再试一下usleep(100000)
while (!(__sync_bool_compare_and_swap (&mutex,lock, 1) ))usleep(100000); //之前是10000,现在改成100000了,也就是0.1秒。
[adapter@ZHEJIANG test3]$ ./nolock
花费时间:0秒 942445微秒
结果:count = 20000000
哦,现在开始速度慢了。

执行环境:
gcc版本信息:
[adapter@ZHEJIANG test3]$ g++ -v
Using built-in specs.
Target: x86_64-redhat-linux
gcc version 4.4.5 20110214 (Red Hat 4.4.5-6) (GCC)

cpu信息:
[adapter@ZHEJIANG test3]$ cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c
      4  Intel(R) Core(TM) i5-3470 CPU @ 3.20GHz

通过编程测试及测试得出结论:
1、如果是想用全局变量来做统计操作。而又不得不考虑多线程间的互斥访问的话,最好使用编译器支持的原子操作函数。
再满足互斥访问的前提下,编程最简单,效率最高。
2、lock-free,无锁编程方式确实能够比传统加锁方式效率高,经上面测试可以发现,可以快到5倍左右。所以在高并发程序中
采用无锁编程的方式可以进一步提高程序效率。
3、但是,得对无锁方式有足够熟悉的了解,不然效率反而会更低。而且容易出错。
4、没想明白的疑问:为什么上面的循环检测时,加uleep比不加,效率更高。为什么在一定程度上,usleep越久效率越高?
请高手路过的时候,为小弟解答一下。谢谢。

0 0