Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupt on a processor while another process is spinning for lock

There is one spin lock in my code which is shared between two threads. When one thread is holding the lock and the other thread is trying to get the lock, the second thread will keep spinning on a processor. So what will happen if an interrupt happens on the processor where the thread is spinning for the lock?

I have used spin_lock() to take the lock and not spin_lock_irqsave() as I dont want to disable interrupt on local processor.

As I checked the code of the spin_lock() function in the kernel, I find that preemption is disabled by default and not any IRQ. So I assume the interrupt will get priority over the spinning thread. So what will be the meaning of spin lock being a non-sleeping lock?

like image 965
Saturn Avatar asked Mar 27 '17 09:03

Saturn


1 Answers

So what will happen if an interrupt happens on the processor where the thread is spinning for the lock?

The interrupt will happen. There's no reason for it not to. After the interrupt returns, the process will go back to spinning.

So what will be the meaning of spin lock being a non sleeping lock?

It means that, threads waiting for the lock to be released will run a tight loop checking the lock state instead of going to sleep to let other threads use the processor.

Sleeping is what happens when a thread yields the processor either as a result of a request for a resource that isn't available or as a result of being pre-empted.

Pre-emption is disabled for threads that hold spin locks (note: not threads that are spinning waiting for the lock) because it would be a disaster for a thread holding a spin lock to go to sleep. Imagine a two CPU system where one thread holds a lock and another is spinning on it and the first thread is swapped out for a third thread that also tries to acquire the lock. Suddenly you have two threads spinning and the system will effectively stop until one of them is swapped out. In the worst case scenario, the system will deadlock.

Spin locks can disable interrupts because interrupt routines are allowed to acquire spin locks. If an interrupt tries to acquire a spin lock that is held by a thread running on the same processor, that processor will be deadlocked.

Here is a good resource for learning more about spin locks.

http://www.makelinux.net/ldd3/chp-5-sect-5

like image 128
JeremyP Avatar answered Oct 05 '22 18:10

JeremyP