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

℡╲_俬逩灬. 提交于 2019-12-10 18:55:42

问题


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

回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/9117048/why-it-isnt-advised-to-call-the-release-method-of-a-binary-semaphore-from-ins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!