On a uniprocessor machine with preemption disabled, what will happen internally when we say spin_lock()?














































On a uniprocessor machine with preemption disabled, what will happen internally when we say spin_lock()?



Imagine a situation where two or more process require dedicated access to a shared resource, 

Yes as you guessed this might lead to many abnormalities hence the processes need a mechanism for enforcing limits on access to a resource.


Locks provide such mechanism, each thread has to acquire the  lock before accessing the corresponding data. The basic form of locking in the Linux kernel is the spinlock.



Spinlock is a lock which causes a thread trying to acquire it to simply wait in a loop (or spin) while repeatedly checking if the lock is available or not. Spinlocks are efficient when threads are likely to be blocked for only short periods (typically ~1ms) however spinlocks become wasteful if held for longer durations as they prevent other threads from running.



The Linux Kernel provides spinlock and semaphores for locking in the kernel. On SMP (Symmetric Multiprocessor System) machines the most widely used locking mechanism is a spinlock and the kernel is designed so that the spinlock is held only for a short duration of time.


But even after great results of spinlock in multiprocessor machines on single processor machines with no preemption they are inappropriate for use, as spinlock is busy-wait lock meaning that a task will spin until it won%u2019t be able to acquire processor now on multiprocessor machines this won%u2019t be a problem as one processor can spin while other can release the lock after execution but in uniprocessor machines with no-preemption if it tries to acquire lock held by another process then it will have to spin thus not allowing CPU to give time to other process which is supposed to release the lock.   



Using spinlocks in uni-processor machines will continuously hinder the execution of thread that currently owns the lock thus not allowing the thread to quickly complete its critical section and release the lock.

On such systems any thread that fails to acquire the lock should be put to sleep and allowed to contend for the resource only when the current thread releases the lock




Comments