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.

你可能感兴趣的:(zephyr)