Let's say process A has an exclusive lock on some shared resource. Is there a way to ensure that after it completes execution, Process B will definitely get the lock (as compared to say, process C being able to get it)?

I am coding in a language that is relatively less used, but didn't want to limit my question to a language-specific tag (in case there are any language-agnostic ways of ensuring the above).


You can't do this with a single mutex, but you could use some semaphores in addition to (or instead of) the mutex. Basically, when A is finished, it would signal B's semaphore. When B or C is finished, it signals an 'everyone else' semaphore. A and C wait on the 'everyone else' semaphore before using the shared resource.

  • What do you mean by "B's semaphore" or "Everyone else semaphore"? I was under the impression that a semaphore is a property of the lock-able object and not a property of each thread. – rahs Sep 5 '19 at 22:27
  • B's semaphore is the semaphore B waits on and A posts to. The other semaphore is waited on by every other thread and posted by every thread except A. A semaphore is a standalone thing. It neither belongs to a thread nor an object. – Karl Bielefeldt Sep 6 '19 at 1:25

No. Unless your language or library makes such a guarantee, you shall not assume that another process will get the lock. You should not either take a gamble on which other process could acquire the lock.

Starvation could for example occur, if process A is too fast to re-acquire the lock while process B is still waiting, or if the process scheduler is not well designed, which might result in B not getting the opportunity to acquire the lock.

Note: I assumed that there would be no deadlock since you said that A could finish its processing (and hence not be stuck waiting for another lock)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.