|
| 1 | +MCS Queue Lock maintains a linked-list for |
| 2 | +threads waiting to enter critical section (CS). |
| 3 | + |
| 4 | +Each thread that wants to enter CS joins at the |
| 5 | +end of the queue, and waits for the thread |
| 6 | +infront of it to finish its CS. |
| 7 | +So, it locks itself and asks the thread infront |
| 8 | +of it, to unlock it when he's done. Atomics |
| 9 | +instructions are used when updating the shared |
| 10 | +queue. Corner cases are also takes care of. |
| 11 | + |
| 12 | +As each thread waits (spins) on its own "locked" |
| 13 | +field, this type of lock is suitable for |
| 14 | +cache-less NUMA architectures. |
| 15 | + |
| 16 | +```java |
| 17 | +1. When thread wants to access critical |
| 18 | + section, it stands at the end of the |
| 19 | + queue (FIFO). |
| 20 | +2a. If there is no one in queue, it goes head |
| 21 | + with its critical section. |
| 22 | +2b. Otherwise, it locks itself and asks the |
| 23 | + thread infront of it to unlock it when its |
| 24 | + done with CS. |
| 25 | +``` |
| 26 | + |
| 27 | +```java |
| 28 | +1. When a thread is done with its critical |
| 29 | + section, it needs to unlock any thread |
| 30 | + standing behind it. |
| 31 | +2a. If there is a thread standing behind, |
| 32 | + then it unlocks him. |
| 33 | +2b. Otherwise it tries to mark queue as empty. |
| 34 | + If no one is joining, it leaves. |
| 35 | +2c. If there is a thread trying to join the |
| 36 | + queue, it waits until he is done, and then |
| 37 | + unlocks him, and leaves. |
| 38 | +``` |
| 39 | + |
| 40 | +See [MCSLock.java] for code, [Main.java] for test, and [repl.it] for output. |
| 41 | + |
| 42 | +[MCSLock.java]: https://repl.it/@wolfram77/mcs-lock#MCSLock.java |
| 43 | +[Main.java]: https://repl.it/@wolfram77/mcs-lock#Main.java |
| 44 | +[repl.it]: https://mcs-lock.wolfram77.repl.run |
| 45 | + |
| 46 | + |
| 47 | +### references |
| 48 | + |
| 49 | +- [The Art of Multiprocessor Programming :: Maurice Herlihy, Nir Shavit](https://dl.acm.org/doi/book/10.5555/2385452) |
0 commit comments