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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章