zephyr-原子服务


概念

内核支持名为atomic_t的32位的原子数据类型。一个这种类型的变量可以被task,fiber或者ISR以中断的方式进行读操作。这保证了目标操作不受高优先级上下文的调度的干扰,甚至当高优先级上下文操作同一个变量。

目的

使用仅需要操作一个32位的数据的原子服务来实现对临界资源的处理

Use the atomic services to implement critical section processing that only requires the manipulation of a single 32-bit data item.

注意:使用原子变量通常比使用其他技术来实现对临界区域的访问更为高效,比如用微内核锁(a microkernel mutex),将处理降级到fiber级别(offloading the processing to a fiber)或者锁中断(locking interrupts)

范例

Example: Implementing an Uninterruptible Counter

This code shows how a function can keep track of the number of times it has been invoked. Since the count is incremented atomically, there is no risk that it will become corrupted in mid-increment if the routine is interrupted by the scheduling of a higher priority context that also calls the routine.

atomic_t call_count;

int call_counting_routine(void)
{
    /* increment invocation counter */
    atomic_inc(&call_count);

    /* do rest of routine's processing */
    ...
}

APIs

The following atomic operation APIs are provided by atomic.h:

atomic_get()
Reads an atomic variable.
atomic_set()
Writes an atomic variable.
atomic_clear()
Clears an atomic variable.
atomic_add()
Performs an addition operation on an atomic variable.
atomic_sub()
Performs a subtraction operation on an atomic variable.
atomic_inc()
Performs an increment operation on an atomic variable.
atomic_dec()
Performs a decrement operation on an atomic variable.
atomic_and()
Perform an “and” operation on an atomic variable.
atomic_or()
Perform an “or” operation on an atomic variable.
atomic_xor()
Perform a “xor” operation on an atomic variable.
atomic_nand()
Perform a “nand” operation on an atomic variable.
atomic_cas()
Performs compare-and-set operation on an atomic variable.
atomic_set_bit()
Sets specified bit of an atomic variable to 1.
atomic_clear_bit()
Sets specified bit of an atomic variable to 0.
atomic_test_bit()
Reads specified bit of an atomic variable.
atomic_test_and_set_bit()
Reads specified bit of an atomic variable and sets it to 1.
atomic_test_and_clear_bit()
Reads specified bit of an atomic variable and sets it to 0.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值