I have been reading about MCS locks which I feel is pretty cool. Now that I know how it's implemented the next question is when to use it. Below are my thoughts. Please feel free to add items to the list
1) Ideally should be used when there more than 2 threads we want to synchronise 2) MCS locks reduces the number of cache lines that has to be invalidated. In the worst case, cache lines of 2 CPUs is invalidated.
Is there anything else I'm missing ?
Also can MCS used to implement a mutex instead of a spinlock ?
A code will benefit from using MCS lock when there's a high locks contention, i.e., many threads attempting to acquire a lock simultaneously. When using a simple spin lock, all threads are polling a single shared variable, whereas MCS forms a queue of waiting threads, such that each thread is polling on its predecessor in the queue. Hence cache coherency is much lighter since waiting is performed "locally".
Using MCS to implement a mutex doesn't really makes sense. In mutex, waiting threads are usually queued by the OS and de-scheduled, so there's no polling whatsoever. For example check out pthread's mutex implementation.
I think the other answer by @CodeMoneky1 doesn't really explain "Also can MCS used to implement a mutex instead of a spinlock ?"
The mutex was implemented using spinlock + counter + wait queue. Here the spinlock is usually Test&Set primitive, or using Peterson's solution. I would actually agree that MCS could be an alternative. The reason it is not used is probably the gain is limited. After all the scope of spinlock used in mutex is much smaller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With