Spin locks
Before starting to talk about the condition variables and the true way that the sleep/notify technique should get implemented, let's go back a little bit and use busy-waiting together with mutexes to write a new solution for example 14.6. As a reminder, the example was about having first A and then B printed in the standard output.
The following is the proposed solution that uses a mutex equipped with the spin locking algorithm. The mutex acts as a memory barrier, so we won't have any memory visibility issues, and it effectively synchronizes the tasks P
and Q
over the Done
shared flag:
Concurrent System { Shared State { Done : Boolean = False M : Mutex } Task P { 1.1. print 'A' 1.2. SpinLock(M) 1.2. Done = True 1.3. SpinUnlock(M) } Task Q { 2.1 SpinLock(M) 2.2. While Not Done { 2.3. SpinUnlock(M) 2.4. SpinLock(M) 2.5. } 2.6. SpinUnlock(M) 2.4. print...