Difference between Spinlock and Semaphore

Spinlocks

Spinlocks assume the data you are protecting is accessed in both interrupt-handlers and normal kernel code. If you know your data is unique to user-context kernel code (e.g., a system call), you can use the basic spin_lock() and spin_unlock() methods that acquire and release the specified lock without any interaction with interrupts.

  • Spinlocks should be used to lock data in situations where the lock is not held for a long time, recall that a waiting process will spin, doing nothing, waiting for the lock.
  • You cannot, however, do anything that will sleep while holding a spinlock.
  • If you need a lock that is safe to hold for longer periods of time, safe to sleep with or capable of allowing concurrency to do more than one process at a time, Linux provides the semaphore.

Semaphores

Semaphores in Linux are sleeping locks. Because they cause a task to sleep on contention, instead of spin, they are used in situations where the lock-held time may be long. Conversely, since they have the overhead of putting a task to sleep and subsequently waking it up, they should not be used where the lock-held time is short. Since they sleep, however, they can be used to synchronize user contexts whereas spinlocks cannot. In other words, it is safe to block while holding a semaphore.

Difference

  • In spinlock, The lock is not held for a long time.
  • In Semaphore, The lock is held for a long time
  • Can’t sleep while holding a spinlock
  • Semaphore cause a task to sleep on contention, instead of spin.

Reference – https://www.linuxjournal.com/article/5833

Leave a Comment