Posts Tagged ‘semaphore’

Semaphore Vs Spinlocking

It’s been quite a long time since i updated the blog … Not because i was busy but just because i was too lazy or may be i can say i dint find anything useful to write .

Anyway during the device driver class we had a discussion on implementing Reader/Writer problem in the kernel space to understand wait queues and locking . We started realizing that locking is not as easy as it sounds or as easy as it appeared for those who studied these concepts from galvin . During the demo a open question was posted as to use semaphore or a spin lock for ensuring mutual exclusion for the reader/writer problem . So this tutorial is for those who thinks semaphore mechanism and spin locking are the same.

In a semaphore when we call the down(struct semaphore *) or down_interruptible(struct semaphore*) is that, when the shared resource is locked ( Note : Rem that the shared buffer cannot be locked only instructions that access can be locked) the down call will put the calling process to sleep . So can this mechanism be applied for all synchronization . A big NO!!!!!!!!!! . Suppose we r using a semaphore to sync access to a device in a interrupt handler . Can u put the interrupt handler process to sleep ??? The interrupt handler will only be wakened after quite a long time . I think you should be able to guess the consequences . So what do we use here ???? It’s where the Spinlock kicks in…

The spin lock cannot be put into sleep . It will continuously poll for the processor and it will can be used in process like interrupt handlers . So know with this knowledge which one do we use for Reader/Write problem ???? Take this scenario : Initially the circular buffer is empty and the reader tries to read the data from the buffer . It gets the lock and tries to read from the queue . If it is a spinlock it will not relinquish the processor . So writer process cannot even write the data into buffer . So wat happenns the kernel hangs . The only way is switch of the PC DIRECTLY . No other way . So u must understand how sensitive these issues are and how tough it is to write such high privileged code .

1) We know that the 2.4 is non preemptive .Only one kernel process/thread can run . Then why use synchronization constructs .
2) What is the effect of interrupts in spinlocking ???