10 std::atomic<mcs_node *> next;
11 std::atomic<int> gate;
22 // tail is null when lock is not held
23 std::atomic<mcs_node *> m_tail;
34 ASSERT( m_tail.load() == NULL );
37 // Each thread will have their own guard.
41 mcs_node m_node; // node held on the stack
43 guard(mcs_mutex * t) : m_t(t) { t->lock(this); }
44 ~guard() { m_t->unlock(this); }
56 _lock_acquired = false;
65 @Commit_point_set: Lock_Enqueue_Point1 | Lock_Enqueue_Point2
67 _lock_acquired == false;
69 _lock_acquired = true;
72 void lock(guard * I) {
73 mcs_node * me = &(I->m_node);
76 // not published yet so relaxed :
77 me->next.store(NULL, std::mo_relaxed );
78 me->gate.store(1, std::mo_relaxed );
80 // publish my node as the new tail :
81 mcs_node * pred = m_tail.exchange(me, std::mo_acq_rel);
84 @Commit_point_define_check: pred == NULL
85 @Label: Lock_Enqueue_Point1
90 // unlock of pred can see me in the tail before I fill next
92 // publish me to previous lock-holder :
93 pred->next.store(me, std::mo_release );
95 // (*2) pred not touched any more
97 // now this is the spin -
98 // wait on predecessor setting my flag -
99 rl::linear_backoff bo;
102 my_gate = me->gate.load(std::mo_acquire);
105 @Commit_point_define_check: my_gate == 0
106 @Label: Lock_Enqueue_Point2
118 Unlock_Point_Success_1 | Unlock_Point_Success_2
120 _lock_acquired == true
122 _lock_acquired = false;
125 void unlock(guard * I) {
126 mcs_node * me = &(I->m_node);
128 mcs_node * next = me->next.load(std::mo_acquire);
131 mcs_node * tail_was_me = me;
133 success = m_tail.compare_exchange_strong(
134 tail_was_me,NULL,std::mo_acq_rel);
137 @Commit_point_define_check: success == true
138 @Label: Unlock_Point_Success_1
143 // got null in tail, mutex is unlocked
147 // (*1) catch the race :
148 rl::linear_backoff bo;
150 next = me->next.load(std::mo_acquire);
157 // (*2) - store to next must be done,
158 // so no locker can be viewing my node any more
161 next->gate.store( 0, std::mo_release );
164 @Commit_point_define_check: true
165 @Label: Unlock_Point_Success_2