One option for using spin locks is if you expect very low competition, but there will be a lot of them. If you do not need support for recursive locking, spin locking can be implemented in one byte, and if the conflict is very low, the waste of the processor cycle is negligible.
For practical use, I often have arrays of thousands of elements, where updates for different elements of the array can safely be performed in parallel. The chances of two threads trying to update the same element at the same time are very small (low rivalry), but I need one lock for each element (I will have many of them). In these cases, I usually allocate an ubytes array of the same size as the array that I am updating in parallel, and implement spinlocks inline as (in the D programming language):
while(!atomicCasUbyte(spinLocks[i], 0, 1)) {} myArray[i] = newVal; atomicSetUbyte(spinLocks[i], 0);
On the other hand, if I had to use regular locks, I would have to allocate an array of pointers to objects, and then allocate a Mutex object for each element of this array. In scenarios like the ones described above, this is simply wasteful.
dsimcha Jul 16 '10 at 17:05 2010-07-16 17:05
source share