Sunday, March 9, 2014

What are the Synchronization techniques used in Linux Kernel?

For simple counter variables or for bitwise ------->atomic operations are best methods. 


atomic_t count=ATOMIC_INIT(0); or atomic_set(&count,0);
atomic_read(&count);
atomic_inc(&count);
atomic_dec(&count);
atomic_add(&count,10);
atomic_sub(&count,10); 


Spinlocks are used to hold critical section for short time and can use from interrupt context and locks can not sleep,also called busy wait loops.
fully spinlocks and reader/writer spin locks are available.
spinlock_t my_spinlock;
spin_lock_init( &my_spinlock );
spin_lock( &my_spinlock );

// critical section

spin_unlock( &my_spinlock );

Spinlock variant with local CPU interrupt disable
spin_lock_irqsave( &my_spinlock, flags );

// critical section

spin_unlock_irqrestore( &my_spinlock, flags );
if your kernel thread shares data with a bottom half,
spin_lock_bh( &my_spinlock );

// critical section

spin_unlock_bh( &my_spinlock );

If we have more readers than writers for our shared resource
Reader/writer spinlock can be used 

 
rwlock_t my_rwlock;

rwlock_init( &my_rwlock );

write_lock( &my_rwlock );

// critical section -- can read and write

write_unlock( &my_rwlock );


read_lock( &my_rwlock );

// critical section -- can read only

read_unlock( &my_rwlock ); 



Mutexs are used when we hold lock for longer time and if we use from process context.
DEFINE_MUTEX( my_mutex );
mutex_lock( &my_mutex );
mutex_unlock( &my_mutex );

1 comment: