Linux2.6内核的原子操作的实现


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

1.  #include</usr/src/linux-headers-2.6.35-22/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; } 

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; }

这两组函数的区别在于第一组返回更新前的值,第二组返回更新后的值.

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

1.  #ifndef LIBDRM_ATOMICS_H

2.  #define LIBDRM_ATOMICS_H

3.  #define HAS_ATOMIC_OPS 1

4.  

5.  typedef struct {

6.      volatile int atomic;

7.  } atomic_t;

8.  

9.  # define atomic_read(x) ((x)->atomic)

10. # define atomic_set(x, val) ((x)->atomic = (val))

11. # define atomic_inc(x) ((void) __sync_fetch_and_add (&(x)->atomic, 1))

12. # define atomic_dec_and_test(x) (__sync_fetch_and_add (&(x)->atomic, -1) == 1)

13. # define atomic_add(x, v) ((void) __sync_add_and_fetch(&(x)->atomic, (v)))

14. # define atomic_dec(x, v) ((void) __sync_sub_and_fetch(&(x)->atomic, (v)))

15. # define atomic_cmpxchg(x, oldv, newv) __sync_val_compare_and_swap (&(x)->atomic, oldv, newv)

16. #define atomic_sub(x,v) atomic_dec(x,v)

17. #define atomic_init(a,v) atomic_set(a,v)

18. #endif18:58:34

相关内容