Belphegor
Belphegor

Reputation: 1843

How do "locks" work in programs for protecting critical sections?

I am currently studying locks and I am confused about the following example of using locks to protect critical sections of code.

Here is my question:

If the Deposit function acquires the lock first, does that mean that the Remove function must wait for the Deposit function to release the lock before being able to do anything else? In other words Remove will be stuck at lock->acquire until Deposit function does lock->release? enter image description here

Upvotes: 1

Views: 91

Answers (1)

skypjack
skypjack

Reputation: 50540

Note that you have multiple actors: lock, on which to invoke the lock operation, and condition variables (named notEmpty and notFull), on which to wait.
Because the question is about lock, the response is - yes.
The remove will either enter the function or wake up from the wait condition and try to acquire the lock.
Anyway, if the deposit function is using it (that is, it has a lock on it, it has acquired it) the remove function will hang on that lock until it is freed (or, even better, released). Note also that when you wait on a condition variable, the lock is automatically released and reacquired once you wake up. Because of that, the function is not holding the lock forever, that's all.

Upvotes: 1

Related Questions