Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use MCS lock

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 ?

like image 729
KodeWarrior Avatar asked Mar 20 '23 04:03

KodeWarrior


2 Answers

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.

like image 105
CodeMonkey1 Avatar answered Apr 06 '23 00:04

CodeMonkey1


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.

like image 22
Junchuan Avatar answered Apr 06 '23 00:04

Junchuan