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

有个/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默认搜索路径下,即使像下面这样强行指定路径,还是会出现编译错误。


#include

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

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

type __sync_fetch_and_add (type *ptr, type value, ...)
type __sync_fetch_and_sub (type *ptr, type value, ...)
type __sync_fetch_and_or (type *ptr, type value, ...)
type __sync_fetch_and_and (type *ptr, type value, ...)
type __sync_fetch_and_xor (type *ptr, type value, ...)
type __sync_fetch_and_nand (type *ptr, type value, ...)
{ tmp = *ptr; *ptr op= value; return tmp; }
{ tmp = *ptr; *ptr = ~tmp & value; return tmp; } // nand

type __sync_add_and_fetch (type *ptr, type value, ...)
type __sync_sub_and_fetch (type *ptr, type value, ...)
type __sync_or_and_fetch (type *ptr, type value, ...)
type __sync_and_and_fetch (type *ptr, type value, ...)
type __sync_xor_and_fetch (type *ptr, type value, ...)
type __sync_nand_and_fetch (type *ptr, type value, ...)
{ *ptr op= value; return *ptr; }
{ *ptr = ~*ptr & value; return *ptr; } // nand

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


view plainprint?

#include
#include
#include

static int count = 0;

void *test_func(void *arg)
{
int i=0;
for(i=0;i<20000;++i){
__sync_fetch_and_add(&count,1);
}
return NULL;
}

int main(int argc, const char *argv[])
{
pthread_t id[20];
int i = 0;

for(i=0;i<20;++i){
pthread_create(&id[i],NULL,test_func,NULL);
}

for(i=0;i<20;++i){
pthread_join(id[i],NULL);
}

printf("%d/n",count);
return 0;
}

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

http://www.cppblog.com/qinqing1984/archive/2011/08/31/154770.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值