Lock-free vs Spin-lock
Given a piece of code, how do you know if it's lock-based or lock-free? Let's first see two examples. Both of them are multi-thread programs accessing a shared variable and incrementing it.
Here is the version by using lock-free programming.
Here is the version of spin-lock for the same purpose.
Let's see the result and performance of the above two programs (averaged on 10 runs).
Lock-free:
Spin-lock:
From the above result, we could see that the lock-free program is better than the spin-lock program. For the lock-free program, the key code is from line 9 to 11; for the spin-lock program, the key code is from line 10 to 15. They're both loops and look very similar. How come they perform differently?
Let's see by an example.
Lock-free:
Spin-lock
There are 4 threads modifying the shared variable count
, and they try to get access to the shared variable count
and increment it. From the above two images, we could see that in the lock-free program, while thread 1 is accessing the shared variable count
, other threads could also get access to the count
and make progress for the program.
However, for the lock-based program, while thread 1 is accessing the shared variable count
, it holds the lock and other threads could not access the count
but only busy-wait. So, here, we could see the difference between them.
For the lock-free program, every thread could get access to the shared object and make progress for the program no matter whether another thread is accessing the shared object or not, though sometimes there could be conflict (e.g. Thread 1 should redo its work). However, for the lock-based program, if one thread is accessing the shared object, other threads would be blocked and have no way to get access to the shared object. This is also the reason why the above lock-free program is faster than the lock-based program.
Last updated
Was this helpful?