I'm thinking about how the feature "prevent from context switch" is achieved in Linux for a spinlock. A big picture / pseudocode is acceptable since I just what to know the logic behind it.


Spinlock is not a Linux feature, it is a very simple CPU feature, at least on most CPUs.

Spinlock doesn't prevent from context switching. Disabling context switching would also disable multitasking, which is unwanted on Linux in most cases.

However, spinlocks are protected from context switching. The essence of the spinlock is that a lock attempt happens in a single CPU command. No context switching can break a process inside a CPU command, only after that.

Implementation is not OS-specific, it is CPU-specific: it requires a mnemonic which can exchange the content of a register and a memory address, atomically. On x86, it can happen by xchg.

  • I found that all my confusion is from my misused "prevent from" context switching, which made me thought that it would never give CPU to another process... . Thanks for helps! – ptr_user7813604 Dec 30 '18 at 2:35
  • From your "a lock attempt happens in a single CPU command" so can I say that context switch will finally happen when return to userspace after the timer ISR, no matter a process hold the spinlock or not? – ptr_user7813604 Dec 30 '18 at 2:44
  • 1
    @ptr_user7813604 Yes. Spinlock only garantees that no inconsistent state will happen, it doesn't matter, when context switches will break the execution. However, it can only try to lock a lock. There is no "wait until the lock will free" primitive in spinlock, it is its largest disadvantage. – peterh Dec 30 '18 at 13:30
  • Thanks for your perfect explanation! I may be busy tomorrow so I think this is the last important thing to say today: Happy new year:)! – ptr_user7813604 Dec 30 '18 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.