asilvester635
asilvester635

Reputation: 81

How does a mutex lock work?

I'm currently studying how mutex lock works. I think I kind of have a grip on it. Is my assumption below the image correct? Here we have two processes, Pi and Pj, that wants to execute their critical section and I try to explain how a mutex lock works to prevent a race condition from happening.

enter image description here

Pi tries to acquire the lock with acquire(). In the beginning, no process is executing its critical section, therefore available will be true. Inside acquire’s while loop, the condition will be false and it will not “busy wait” and available will be set to false. The reason that available is set to false is to prevent other processes from entering their critical section. Pj, on the other hand, would not be allowed to execute its critical section since available was set to false by Pi. !available will be true, therefore Pj will be stuck in “busy wait”.

Once Pi finishes executing its critical section, it calls release(). The release method resets the boolean variable available to true. Once available has been set to true, Pj will stop with the “busy wait” because now !availale will give a false value. Pj will set available to false and execute its critical section. The cycle repeats itself for the next process wanting to acquire a lock to execute its critical section

Upvotes: 1

Views: 862

Answers (2)

yihhe
yihhe

Reputation: 11

The lock implemented above is somewhat similar to spin lock, except that it should use CAS(compare-and-swap) atomic operation to guarantee correctness. The general idea to implement mutex acquire() is:

  1. Check whether the mutex is available
  2. If available, then mark the mutex as used. Otherwise, yield until scheduler runs the thread again after the mutex is released.

Upvotes: 1

Alexander
Alexander

Reputation: 63167

You explanation is correct, but don't worry too much about the implementation of acquire().

For one, this implementation of acquire() has a race condition on available.

This code is merely an example to illustrate the usage of a mutex (in this case, a spinlock), and glances over the details of the implementation.

Upvotes: 1

Related Questions