Spinlock versus Semaphore

后端 未结 11 699
广开言路
广开言路 2020-11-28 17:19

What are the basic differences between a semaphore & spin-lock?

When would we use a semaphore over a spin-lock?

11条回答
  •  孤城傲影
    2020-11-28 18:01

    very simply, a semaphore is a "yielding" synchronisation object, a spinlock is a 'busywait' one. (there's a little more to semaphores in that they synchronise several threads, unlike a mutex or guard or monitor or critical section that protects a code region from a single thread)

    You'd use a semaphore in more circumstances, but use a spinlock where you are going to lock for a very short time - there is a cost to locking especially if you lock a lot. In such cases it can be more efficient to spinlock for a little while waiting for the protected resource to become unlocked. Obviously there is a performance hit if you spin for too long.

    typically if you spin for longer than a thread quantum, then you should use a semaphore.

提交回复
热议问题