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

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

1.整数原子操作

数据类型为:

typedefstruct {

volatileint counter;

}atomic_t;


内核同步机制——原子操作_第1张图片

为了保持内核在各个平台兼容,以前规定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 */


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


你可能感兴趣的:(exception,测试,Integer,平台)