Showing posts with label spinlock. Show all posts
Showing posts with label spinlock. Show all posts

Tuesday, February 11, 2014

Semaphore

As we discussed in previous post, Spinlock is spinning lock, the same way Semaphore is sleeping lock.
So think of a scenario in which a task want to acquire a semaphore which is not available, so it will go to sleep  and semaphore will put it on a wait queue. Once this semaphore becomes available, scheduler will invoke any of the task on this waitqueue.

Properties:
1. As the task holding semaphore can sleep, it is best suitable for the task which runs for longer duration.
2. As the task holding semaphore can sleep, it can only be used in Process Context.
3. Task cant hold a spinlock if it wants to acquire a semaphore. Because task might want to sleep while waiting for semaphore, but this will cause processor to sleep for infinte time(if it is holding spinlock), as there is no one to wake it up. 

Monday, February 10, 2014

Spin lock

Lets start with spin lock. First we will understand what is it and further I will try to cover few doubts about it, which could be quite useful in Interviews.

What is Spin lock :
Spin lock is a lock that can be held by at most one thread of execution. Suppose one thread is trying to acquire a spin lock, so first it will check whether this spinlock is held by other thread or not, if it is available it will acquire the lock otherwise it will constantly keep on checking (busy looping) for this lock.

Properties :
1. It should be held for small duration only, because during the time a spin lock is held no other thread can be scheduled on that processor.
2. On uni processor, if spin lock is held, it means it will now behave as kernel preemption is disable. As no other thread can run.
3. On Multi processor, no other thread will be able to take this spin lock.
4. If interrupt handler needs to use lock, they can use spinlock. Also we must ensure that local interrupts are disable before obtaining the lock. Otherwise, it is possible for an interrupt handler to interrupt the kernel code while lock is held. This in turn will make interrupt handler to spins, waiting for the lock to become available while lock holder thread will wait interrupt handler to complete. This is deadlock.

Now another scenario, Suppose you disabled interrupt on local processor and a process is holding the lock. At the same time interrupt came on other processor, it will make process to release the spinlock.