Atomic Operation

Atomic Operations



Linux kernel provides feature to perform some operation atomically i.e. user need not to block any thing kernel itself takes care that no context switch will happen during the operation.  They are fastest lock but are limited to some operations only.


The atomic operators are ideal for situations where the data you need to protect is simple, such as a counter. While simple, the atomic API provides a number of operators for a variety of situations. Here's a sample use of the API.


To declare an atomic variable, you simply declare a variable of type atomic_t. This structure contains a single int element. Next, you ensure that your atomic variable is initialized using the ATOMIC_INIT symbolic constant.
atomic_t counter = ATOMIC_INIT(0);

The atomic API supports a rich set of functions covering many use cases. You can read the contents of an atomic variable with atomic_read and also add a specific value to a variable with atomic_add. The most common operation is to simply increment/decrement the variable, which is provided with atomic_inc/atomic_dec.
Some simple atomic operations are listed below:


atomic_read( &counter );
atomic_add( 1, &counter );
atomic_inc( &counter );
atomic_sub( 1, &counter );
atomic_dec( &counter );

The API also supports a number of other common use cases, including the operate-and-test routines. These allow the atomic variable to be manipulated and then tested.


if (atomic_sub_and_test( 1, &counter )) {
  // counter is zero
}
if (atomic_dec_and_test( &counter )) {
  // counter is zero
}
if (atomic_inc_and_test( &counter )) {
  // counter is zero
}
if (atomic_add_negative( 1, &counter )) {
  // counter is less than zero
}

val = atomic_add_return( 1, &counter ));
val = atomic_sub_return( 1, &counter ));

You'll also find support for bitmask operations with the atomic API.


unsigned long my_bitmask;

atomic_clear_mask( 0, &my_bitmask );
atomic_set_mask( (<< 24), &amp;my_bitmask );

Note that atomic operations are slower than normal operation, and so should not be used unnecessarily.





Previous (Spin Lock)                                                                              Next(Summary)

No comments:

Simple theme. Powered by Blogger.