没有atomic.h后如何在Linux实现原子操作


今天同事告诉我说有个/usr/include/alsa/iatomic.h,也能实现原子操作,使用的时候#include<alsa/iatomic.h>就可以了,原有的atomic系列函数这里都有,不过我还没试过。

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

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

  1. #include</usr/src/linux-headers-2.6.27-7/include/asm-x86/atomic.h>  

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 <stdio.h>   
  2. #include <pthread.h>   
  3. #include <stdlib.h>   
  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系统上,例如

  1. #define atomic_inc(x) __sync_add_and_fetch((x),1)   
  2. #define atomic_dec(x) __sync_sub_and_fetch((x),1)   
  3. #define atomic_add(x,y) __sync_add_and_fetch((x),(y))   
  4. #define atomic_sub(x,y) __sync_sub_and_fetch((x),(y))  

相关内容