lock-free vs spin-lock
So, 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-threads get access to a shared variable and do the addition on 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(average result of running each program 10 times) and performance of the above two programs.
Lock-free:
Lock-based:
From the above result, we could see that the lock-free program is better than the spin-lock program. Let's see the addition part of both programs. (For the lock-free program, it is the code from line 11 to 13, for the spin-lock program, it is the code from line 12 to 15) They're both loops, and looks very similar. Moreover, we can loop at both loops for a period of time. How come they're at the opposite sides of the locking/lock-free distinction?!
Let's first see an example.
lock-free
lock-based
There are 4 threads modifying the shared variable count, and they try to get access to the shared variable count and do the addition on 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 busy-waiting. 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.(Although sometimes, there could be some conflicts(just like thread 1), and the thread 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. Also, from the above images, we could also know why the above lock-free program is quicker than the lock-based program.
Last updated