设为首页 加入收藏

TOP

Linux2.6内核的原子操作的实现
2014-11-24 08:15:01 来源: 作者: 【 】 浏览:1
Tags:Linux2.6 内核 原子 操作 实现

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


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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux设备驱动开发中有关scull模.. 下一篇Linux kernel 2.6.38.2编译编译

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Python爬虫教程(从 (2025-12-26 16:49:14)
·【全269集】B站最详 (2025-12-26 16:49:11)
·Python爬虫详解:原 (2025-12-26 16:49:09)
·Spring Boot Java: (2025-12-26 16:20:19)
·Spring BootでHello (2025-12-26 16:20:15)