Why it isn't advised to call the release() method of a binary semaphore from inside a finally
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();
}
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).
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).
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
链接地址: http://www.djcxy.com/p/90126.html上一篇: JSP模板继承