问题描述
我一直在努力了解重入锁定和信号量(重入锁定与释放/解锁机制的嵌套)。
I've been trying to understand Reentrant locks and Semaphores ( the nesting of Reentrant locks vs release/unlock mechanism ).
似乎拥有信号量需要你编写一个更彻底测试的应用程序,因为release()方法不检查释放许可证的线程是否实际持有它。当我测试我的测试代码时,我发现这可能随后增加超过初始限制的许可数量。另一方面,如果一个线程在调用unlock方法时没有持有重入锁,我们会得到一个IllegalMonitorException。
It seems that having a Semaphore requires you to write a more thoroughly tested application because the release() method does not check if the thread releasing the permit is actually holding it. When I tested my test code, I found out that this may subsequently increase the number of permits beyond the initial limit. On the other hand, if a thread is not holding a reentrant lock when it invokes the unlock method, we get an IllegalMonitorException.
所以说那里是正确的没有真正的理由拥有二进制信号量,因为二进制信号量可以做的所有事情也可以由ReentrantLock完成。如果我们使用二进制信号量,我们必须检查整个方法调用堆栈以查看之前是否获得了许可证(如果有可能进行后续获取,它也会被释放 - 如果某个版本没有继续获取它可能会阻止它等等)。此外,由于重入锁也为每个对象提供一个锁,所以更喜欢将重入锁定为二进制信号量是不是更好?
So would it be right to say that there is no real reason ever to have a binary semaphore as everything that a binary semaphore can do can also be done by a ReentrantLock. If we use binary semaphores we would have to check the entire method call stack to see if a permit was acquired before ( also was it released too if there is a possibility of a subsequent acquire - which might block if a release does not proceed it and so on ). Also since reentrant locks also provide one lock per object, isn't it always a better idea to prefer a reentrant lock to a binary semaphore?
我在这里查了一个帖子谈到二进制信号量和互斥量之间的区别,但有没有像Java中的互斥量这样的东西?
I have checked a post here that talks about difference between a binary semaphore and a mutex but is there a thing like a mutex in Java?
谢谢,
Chan。
Thanks,Chan.
PS - 我在另一个论坛发布了这个问题()我还没有收到回复。我以为我也会在这里发布,看看我能得到什么。
P.S - I had posted this question in another forum ( http://www.coderanch.com/t/615796/threads/java/reason-prefer-binary-Semaphore-Reentrant ) and I haven't received a response yet. I thought I'd post it here as well to see what I can get.
推荐答案
如果您只需要可重入互斥,那么是的,没有理由在ReentrantLock上使用二进制信号量。如果由于任何原因你需要非所有权释放语义,那么显然信号量是你唯一的选择。
If all you need is reentrant mutual exclusion, then yes, there is no reason to use a binary semaphore over a ReentrantLock. If for any reason you need non-ownership-release semantics then obviously semaphore is your only choice.
它取决于在需要。像之前解释的那样,如果你需要一个简单的互斥锁,那就不要选择一个信号量。如果多个线程(但数量有限)可以进入临界区,则可以通过线程限制或信号量来执行此操作。
It depends on the need. Like previously explained, if you need a simple mutex, then don't choose a semaphore. If more than one thread (but a limited number) can enter a critical section you can do this through either thread-confinement or a semaphore.
ReentrantLock
和 synchronized
是Java中互斥锁的示例。
ReentrantLock
and synchronized
are examples of mutexes in Java.
这篇关于Binary Semaphore vs ReentrantLock的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!