Sunday, May 22, 2011

Kernel synchronization methods

Hi guys, From our last talk about Synchronization I would like to talk about The kernel synchronization methods: Recently I have posted few posts about the importance of avoiding race conditions. Today I’ll be talking how to avoid it using the methods which are supplied in the kernel environment. So for those of you who ask them self how come the usual integer operations aren’t safe, I’ll explain: As we know each c commands is translated into assembly code. Atomic Integer Operations Those Atomic integer operations operate on a special type of variable called: atomic_t, which should be used in exchange to the int type. Using atomic functions which accept only the atomic_t type ensures that the atomic operations are used only with these special types. You can find the definition of atomic_t type in the <linux/types.h> , it looks like this:
Typdef struct
{
   volatile int counter;
} atomic_t;
We can see according to definition the atomic_t is declared with volatile keyword, this way we make sure the compiler won’t optimize access to the value – because it’s important the atomic operations receive the correct memory address and not an alias. The actual declarations of the atomic operations are in <asm/atomic.h>, take a look :-) Of course it’s architecture depends, so you should check if your architecture of choice is well supported in the kernel code. So let’s say I would like to declare a myPool which is shared among few threads, for example:
atomic_t myPool;
atomic_set(&amp;myPool,7);   //myCounter=7 
atomic_inc(&amp;myPool);     //myCounter=myCounter+1=8
atomic_sub (5,&amp;myPool);  //myCounter=myCounter-5=3
atomic_dec(&amp;myPool);     //myCounter=myCounter-1=2
If we would like to decrease and test the contents of the variable we will use the operation:
atomic_dec_and_test(&myPool);
The atomic_dec_and_test function would decrease by one the variable contents and then tests the result in case it’s zero it return true, otherwise it returns false. All those operations are for 32 bit architecture, there are bunch of similar commands for a 64 bit architecture, the definition looks like:
typdef struct
{
   volatile long counter;
} atomic_t;

The volatile prevents the compiler from caching the value locally, forcing it to be retrieve where ever there is access to it.

Example for a simple command is: atomic64_set(56,&myPool); etc..

No comments:

Post a Comment

About