Spin locks in Linux systems (clearly illustrated in two pictures)

Insert image description here
Insert image description here
Summary: The spin lock under
multiple CPUs adopts a busy waiting (spin in place) mechanism . Although the busy waiting thread occupies its cpu, other threads can still be executed on other CPUs. Therefore, the critical section code between the spin lock locking and unlocking should be as short as possible, preferably no more than 5 lines, otherwise too many CPU resources will be wasted by busy waiting threads.

The spin lock under a single CPU adopts the sleep mechanism , because busy waiting will cause only one poor CPU to be occupied by it, and the thread with the spin lock cannot be executed and cannot release the lock, which will cause a deadlock.


Some functional interfaces about spin locks

The spin_lock function is declared in the kernel file include\linux\spinlock.h, as shown in the following table:

Function name effect
spin_lock_init(_lock) Initialize the spin lock to unlock state
void spin_lock(spinlock_t *lock) Acquire the spin lock (lock), and the lock must be obtained after returning
int spin_trylock(spinlock_t *lock) Try to obtain the spin lock, return 1 if the lock is successfully obtained, otherwise return 0
void spin_unlock(spinlock_t *lock) Release the spin lock, or unlock
int spin_is_locked(spinlock_t *lock) Returns the status of the spin lock. If it is locked, it returns 1, otherwise it returns 0.

The locking and unlocking functions of the spin lock are: spin_lock , spin_unlock , and various suffixes can be added , which means that additional things will be done while locking or unlocking:

suffix describe
_bh() Disable the lower half (soft interrupt) when locking, and enable the lower half (soft interrupt) when unlocking
_irq() Interrupts are disabled when locked and enabled when unlocked.
_irqsave/restore() Disable and interrupt and record the state when locking, and restore the interrupted state to the recorded state when unlocking

Guess you like

Origin blog.csdn.net/HuangChen666/article/details/132199903