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();
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With