2

When a thread on Linux is spinning and trying to get the spinlock, Is there no chance this thread can be preempted?

EDIT:
I just want to make sure some thing. On a "UP" system, and there is no interrupt handler will access this spinlock. If the thread who is spinning and trying to get the spinlock can be preempted, I think in this case, the critical section which spinlock protects can call sleep, since the thread holding spinlock can be re-scheduled back to CPU.

specializt
  • 1,913
  • 15
  • 26
Nan Xiao
  • 16,671
  • 18
  • 103
  • 164
  • @ChristopherCreutzig: Just update the OP. – Nan Xiao Nov 26 '15 at 09:27
  • @ChristopherCreutzig: I come across this [topic](http://stackoverflow.com/questions/4752031/why-cant-you-sleep-while-holding-spinlock), so just wonder what conditions must be met, if allowing thread holding spinlock can sleep. So if the contending spinlock thread can be preempted on `UP` system, then the holding spinlock thread can reschedule to release the spinlock, the contending spinlock thread can acquire the spinlock. – Nan Xiao Nov 26 '15 at 09:39

1 Answers1

2

No it cannot be preempted: see the code (taken from linux sources) http://lxr.free-electrons.com/source/include/linux/spinlock_api_smp.h?v=2.6.32#L241

241 static inline unsigned long __spin_lock_irqsave(spinlock_t *lock)
242 {
243         unsigned long flags;
244 
245         local_irq_save(flags);
246         preempt_disable();
247         spin_acquire(&lock->dep_map, 0, 0, _RET_IP_);
248         /*
249          * On lockdep we dont want the hand-coded irq-enable of
250          * _raw_spin_lock_flags() code, because lockdep assumes
251          * that interrupts are not re-enabled during lock-acquire:
252          */
253 #ifdef CONFIG_LOCKDEP
254         LOCK_CONTENDED(lock, _raw_spin_trylock, _raw_spin_lock);
255 #else
256         _raw_spin_lock_flags(lock, &flags);
257 #endif
258         return flags;
259 }
260 
[...]
349 static inline void __spin_unlock(spinlock_t *lock)
350 {
351         spin_release(&lock->dep_map, 1, _RET_IP_);
352         _raw_spin_unlock(lock);
353         preempt_enable();
354 }

see lines 246 and 353

By the way It is generally a bad idea to sleep while holding a lock (spinlock or not)

OznOg
  • 4,440
  • 2
  • 26
  • 35
  • yeah, sleeping during a lock pretty much defeats the entire purpose of the lock itself ... either unlock and sleep or dont sleep at all, thats programming basics right there – specializt Nov 26 '15 at 11:31