The difference and selection principle of Linux spin lock and mutual exclusion lock

One, the difference

1. The difference in implementation: mutual exclusion locks are implemented based on spin locks, so spin locks are more low-level than mutual exclusion locks.

2. The difference in overhead: when the mutex lock cannot be acquired, a context switch will occur and sleep, while the spin lock "spins" in place until it is acquired.

3. The difference in usage scenarios: the mutex can only be used in the incoming (line) process, not in the interrupt, and the spin lock can be used in the interrupt.

4. The difference in the way of use: mutex locks can only be released by the process of acquiring the lock, while spin locks do not have this restriction, but locking and unlocking are generally used in pairs.

2. Selection principle

Based on the above differences, the following three selection principles can be drawn:

1. When the critical area to be protected is small, spin locks should be used, otherwise, mutual exclusion locks should be used. Because when the lock cannot be acquired, the overhead of the mutex lock is context switching, and the overhead of context switching is very large. However, when the execution time cost of the critical section is greater than the context switch cost, it is appropriate to use a mutex lock. In this case, using a spin lock will cause the CPU to idle until the other execution units are unlocked (it is better to have a context switch). Reduce system efficiency.

2. The critical section protected by the spin lock cannot have a function that causes context switching (sleep), but the mutex can. If a context switch occurs in the critical section protected by the spin lock, and the process (line) executed after the context is switched to acquire the spin lock, this will inevitably lead to the occurrence of a deadlock. In addition, the critical section protected by the mutex should also try to avoid blocking (for example, requesting another mutex), otherwise deadlock is prone to occur.

3. If the protected critical section is in an interrupt, then only spin locks can be used. Because mutexes may cause blocking, interrupts cannot be blocked.

Guess you like

Origin blog.csdn.net/qq_27575841/article/details/109440871