linux ---- spin locks

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/yuewen2008/article/details/90452376
What is the spin lock?

Spinlock (spinlock): it refers to the time when a thread to acquire the lock, if the lock has been acquired by other threads, then the thread will wait for the cycle, and then continue to determine whether the lock is successfully acquired, until the lock is acquired before exit the loop.

Thread acquiring the lock has been active, but did not perform any tasks effectively, the use of this lock will cause busy-waiting.

It is proposed to achieve the protection of shared resources and a locking mechanism. In fact, the spin mutex lock and more similar, they are made to address the use of an exclusive resources. Whether mutex or spin lock, at any moment, can only have a holder, it said, you can only have at most one execution unit at any time to acquire a lock. But the two slightly different scheduling mechanisms. For the mutex, if the resource is already occupied, the resource request can only go to sleep. But the spin lock without causing the caller to sleep, if the spin lock has been held another execution unit, the caller has been to see whether the spin cycle lock holder has released the lock where the word "spin" It is so named.

The existence of spin-lock problem

If a thread holding a lock for too long, it will lead to other threads waiting to acquire the lock into the loop to wait, consume CPU. Improper use can cause high CPU utilization.

The advantage of spin locks

Spin lock state does not make the thread switch occurs has been in user mode, i.e., the thread has been active; does not cause the thread to enter the blocked state, reducing unnecessary context switching, execution speed
non-spin lock is not acquired when the lock will enter the blocking state, so that the kernel mode, when the lock is acquired when the need to recover from kernel mode, for a thread context switch. (Kernel thread is blocked after entering (Linux) scheduling state, this will cause the system to switch back and forth between user mode and kernel mode, seriously affect the performance of the lock)

Spin and mutex lock

Spin lock and mutex is to implement mechanisms to protect shared resources.
Whether or spin lock mutex, at any time, you can only have a holder.
Acquire the mutex thread, if the lock has been occupied, the thread will go to sleep; get the spin lock thread does not sleep, but has been waiting for the lock release cycle.

Guess you like

Origin blog.csdn.net/yuewen2008/article/details/90452376