Spinlocks are incredibly fast when there is 1 consumer and 1 producer. When there are more threads they are far slower than a semaphore
or conditional variable implementation.
For our spinlock we’ll be using atomic_compare_and_swap. An atomic operation that takes three args
- *int to the lock
- Expected value of the lock
- The value to swap into the lock if the value from step 2 is found in the lock.
It then returns the found value of the spinlock which you must check. If the value is the value from #2 you’ve acquired the lock.
If not you must keep spinning.
Note that all the code is valid I just haven’t included the struct used for passing around the spinlock and buffer as
that will be specific to your buffer.
The approach is thoroughly described in the code comments.