A spin lock is a non-blocking lock. That is to say, if a thread needs to obtain the spin lock but the lock has been occupied by other threads, the thread will not be suspended, instead, it is constantly consuming CPU time and constantly trying to obtain the spin lock.
The mutex is a blocking lock. When a thread cannot obtain the mutex, the thread will be suspended directly, and the thread no longer consumes CPU time. When other threads release the mutex, the operating system will activate the suspended thread and put it into operation.
The two locks apply to different scenarios:
If it is a multi-core processor, it is cost-effective to use the spin lock if it is estimated that the thread waits for the lock for a short time and is shorter than the thread's two context switches.
If it is a multi-core processor, if it is estimated that the thread waits for a lock for a long time, at least longer than the two thread context switches, we recommend that you use mutex.
If it is a single-core processor, it is generally not recommended to use a spin lock. Because only one thread is in the running state at the same time, if the running thread finds that the lock cannot be obtained, it can only wait for unlocking, but because it does not stop, therefore, the thread that gets the lock cannot enter the running state. It can be scheduled only when the running thread has used up the time slice allocated to the operating system. In this case, it is costly to use the spin lock.
If the lock code is often called, but the competition rarely happens, the spin lock should be used first. The spin lock overhead is relatively small and the mutex overhead is large.
References
Multi-core Programming Technology
Linux kernel design and implementation