概念
内核支持名为atomic_t的32位的原子数据类型。一个这种类型的变量可以被task,fiber或者ISR以中断的方式进行读操作。这保证了目标操作不受高优先级上下文的调度的干扰,甚至当高优先级上下文操作同一个变量。
目的
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
:
- Reads an atomic variable.
- Writes an atomic variable.
- Clears an atomic variable.
- Performs an addition operation on an atomic variable.
- Performs a subtraction operation on an atomic variable.
- Performs an increment operation on an atomic variable.
- Performs a decrement operation on an atomic variable.
- Perform an “and” operation on an atomic variable.
- Perform an “or” operation on an atomic variable.
- Perform a “xor” operation on an atomic variable.
- Perform a “nand” operation on an atomic variable.
- Performs compare-and-set operation on an atomic variable.
- Sets specified bit of an atomic variable to 1.
- Sets specified bit of an atomic variable to 0.
- Reads specified bit of an atomic variable.
- Reads specified bit of an atomic variable and sets it to 1.
- Reads specified bit of an atomic variable and sets it to 0.
atomic_get()
atomic_set()
atomic_clear()
atomic_add()
atomic_sub()
atomic_inc()
atomic_dec()
atomic_and()
atomic_or()
atomic_xor()
atomic_nand()
atomic_cas()
atomic_set_bit()
atomic_clear_bit()
atomic_test_bit()
atomic_test_and_set_bit()
atomic_test_and_clear_bit()