Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it isn't advised to call the release() method of a binary semaphore from inside a finally-clause?

To make sure that a Lock is unlocked, it is adviced to call the unlock() method from inside a finally-clause:

lock.lock();
try{
  // critical section which may throw exceptions
} finally {
  lock.unlock();
}

This is to avoid a possible deadlock, in case an exception is thrown from the code in the critical section.

Why isn't the same practice adviced for binary semaphores in equivalent scenarios?

mutex.acquire();
try{
  // critical section which may throw exceptions
} finally {
  mutex.release();
}
like image 665
Marco Lackovic Avatar asked Dec 16 '25 15:12

Marco Lackovic


1 Answers

I would say that is generally the best way to handle them. Semaphores, however have the ability to be released by a separate thread, so in some advanced use cases, this pattern is not possible. (that said, it's possible for Lock lock() and unlock() calls to be in separate methods such that a finally block is not possible as well).

like image 186
jtahlborn Avatar answered Dec 19 '25 04:12

jtahlborn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!