内核同步机制——原子操作

内核为原子操作提供了两组接口。一组操作整数,一个组操作比特位。

1.整数原子操作

数据类型为:

typedefstruct {

volatileint counter;

}atomic_t;



为了保持内核在各个平台兼容,以前规定atomic_t的值不能超过24位(都是SPARC惹的祸),不过现在该规定已经不需要了。

相关操作如下:

voidatomic_set(atomic_t *v, int i);

atomic_tv = ATOMIC_INIT(0);//设置原子变量v的值为整数i

intatomic_read(atomic_t *v);//返回原子变量当前的值

voidatomic_add(int i, atomic_t *v);//i加到原子变量上

voidatomic_sub(int i, atomic_t *v)//从原子变量的值中减去i

voidatomic_inc(atomic_t *v);//增加原子变量的值

voidatomic_dec(atomic_t *v);//减少原子变量的值


执行相关的操作后测试原子变量的值是否为0

Performthe specified operation and test the result; if, after the operation,the atomic value is 0, then the return value is true; otherwise, itis false. Note that there is no atomic_add_and_test.


intatomic_inc_and_test(atomic_t *v);


intatomic_dec_and_test(atomic_t *v);


intatomic_sub_and_test(int i, atomic_t *v);


Addthe integer variable i to v. The return value is true if the resultis negative,false otherwise.

intatomic_add_negative(int i, atomic_t *v);

Behavejust like atomic_add and friends, with the exception that they returnthe new value of the atomic variable to the caller.


intatomic_add_return(int i, atomic_t *v);


intatomic_sub_return(int i, atomic_t *v);


intatomic_inc_return(atomic_t *v);


intatomic_dec_return(atomic_t *v);

最近的内核也提供了64位的版本,即atomic64_t,方法和用法与32位类似,方法名相应的地方换为atomic64


2.位操作

Setsbit number nr in the data item pointed to by addr.

voidset_bit(nr, void *addr);

Clearsthe specified bit in the unsigned long datum that lives at addr. Itssemantics are otherwise the same as set_bit.

voidclear_bit(nr, void *addr);


voidchange_bit(nr, void *addr); // Toggles the bit.


Thisfunction is the only bit operation that doesn’t need to be atomic;it simply returns the current value of the bit.

test_bit(nr,void *addr);


Behaveatomically like those listed previously, except that they also returnthe previous value of the bit.

inttest_and_set_bit(nr, void *addr);


inttest_and_clear_bit(nr, void *addr);


inttest_and_change_bit(nr, void *addr);


使用场景:

/*try to set lock */


while(test_and_set_bit(nr, addr) != 0)

wait_for_a_while();


/*do your work */

/*release lock, and check... */

if(test_and_clear_bit(nr, addr) = = 0)

something_went_wrong(); /* already released: error */


内核也提供了一套非原子位操作函数,函数名就是原子版函数前面加两下划线。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值