Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1758785
  • 博文数量: 290
  • 博客积分: 10653
  • 博客等级: 上将
  • 技术积分: 3178
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-24 23:08
文章存档

2013年(6)

2012年(15)

2011年(25)

2010年(86)

2009年(52)

2008年(66)

2007年(40)

分类: C/C++

2011-12-23 10:37:40

置顶]没有atomic.h后如何在linux实现原子操作
791人阅读 评论(0) 举报

2011-09-06更新

需要使用atomic_add_return函数,发现编译时找不到该函数的入口,阅读iatomic.h后发现在I386和X86_64平台下, 不支持带有return后缀函数,例如atomic_sub_return,atomic_inc_return等,但支持test后缀函数,如 atomic_sub_and_test等。

在其它平台,如powerpc、mips、arm下支持全系列的原子操作。真不知设计这个头文件的人是怎么想的。敲打


2010-12-30更新

今天同事告诉我说有个/usr/include/alsa/iatomic.h,也能实现原子操作,使用的时候#include就可以了,原有的atomic系列函数这里都有,包括atomic_read、atomic_set、 atomic_inc、atomic_add、atomic_sub。

只支持32位数据的原子操作。

-------------------------------正文---------------------------------------

     在Linux2.6.18之后,删除了,GCC提供了内置的原子操 作函数,更适合用户态的程序使用。现在atomic.h在内核头文件中,不在gcc默认搜索路径下,即使像下面这样强行指定路径,还是会出现编译错误。

 

  1. #include  

gcc从4.1.2提供了__sync_*系列的built-in函数,用于提供加减和逻辑运算的原子操作,。

可以对1,2,4或8字节长度的数值类型或指针进行原子操作,其声明如下

  1. type __sync_fetch_and_add (type *ptr, type value, ...)  
  2. type __sync_fetch_and_sub (type *ptr, type value, ...)  
  3. type __sync_fetch_and_or (type *ptr, type value, ...)  
  4. type __sync_fetch_and_and (type *ptr, type value, ...)  
  5. type __sync_fetch_and_xor (type *ptr, type value, ...)  
  6. type __sync_fetch_and_nand (type *ptr, type value, ...)  
  7.           { tmp = *ptr; *ptr op= value; return tmp; }  
  8.           { tmp = *ptr; *ptr = ~tmp & value; return tmp; }   // nand  
  9.   
  10. type __sync_add_and_fetch (type *ptr, type value, ...)  
  11. type __sync_sub_and_fetch (type *ptr, type value, ...)  
  12. type __sync_or_and_fetch (type *ptr, type value, ...)  
  13. type __sync_and_and_fetch (type *ptr, type value, ...)  
  14. type __sync_xor_and_fetch (type *ptr, type value, ...)  
  15. type __sync_nand_and_fetch (type *ptr, type value, ...)  
  16.           { *ptr op= value; return *ptr; }  
  17.           { *ptr = ~*ptr & value; return *ptr; }   // nand  

这两组函数的区别在于第一组返回更新前的值,第二组返回更新后的值,下面的示例引自这里

 

  1. #include   
  2. #include   
  3. #include   
  4.   
  5. static int count = 0;  
  6.   
  7. void *test_func(void *arg)  
  8. {  
  9.         int i=0;  
  10.         for(i=0;i<20000;++i){  
  11.                 __sync_fetch_and_add(&count,1);  
  12.         }  
  13.         return NULL;  
  14. }  
  15.   
  16. int main(int argc, const char *argv[])  
  17. {  
  18.         pthread_t id[20];  
  19.         int i = 0;  
  20.   
  21.         for(i=0;i<20;++i){  
  22.                 pthread_create(&id[i],NULL,test_func,NULL);  
  23.         }  
  24.   
  25.         for(i=0;i<20;++i){  
  26.                 pthread_join(id[i],NULL);  
  27.         }  
  28.   
  29.         printf("%d/n",count);  
  30.         return 0;  
  31. }  

对于使用atomic.h的老代码,可以通过宏定义的方式,移植到高内核版本的linux系统上,例如

http://www.cppblog.com/qinqing1984/archive/2011/08/31/154770.html

阅读(3443) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~