Marco Lackovic
Marco Lackovic

Reputation: 6497

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();
}

Upvotes: 3

Views: 591

Answers (3)

Martin James
Martin James

Reputation: 24857

Because it is not necessary for the thread whose wait on the binary semaphore is successful to be the one that signals it. Threads don't own semaphore units like they do acquired mutexes - any thread can signal a semaphore, (hence their common use in producer-consumer queues).

Upvotes: 1

John Vint
John Vint

Reputation: 40256

I would advise to do it that way. But the main difference between semaphore and lock is that there are no owners of a semaphore. Meaning the thread that acquired the semaphore may not be the one releasing it and that's ok. I would suggest to always release in a finally block at some point

Upvotes: 1

jtahlborn
jtahlborn

Reputation: 53694

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).

Upvotes: 3

Related Questions