如何解释信号量处理操作?
接下来是一个简单的信号量实现。
public class Semaphore {
private boolean signal = false;
public synchronized void take() {
this.signal = true;
this.notify();
}
public synchronized void release() throws InterruptedException {
while (!this.signal) wait();
this.signal = false;
}
}
通过调用 take() 信号量模拟信号获取并唤醒随机选择的线程(如果它确实存在),并且通过调用release(),如果未获取信号,信号量会强制当前(触发)线程等待notify() 但将信号获取设置为 false?
这是否意味着,如果我有 3 个线程的单个信号量,我将必须为代码部分中的每个线程运行 take() - release() 对,这不是线程安全的?
Next is a simple semaphore implementation.
public class Semaphore {
private boolean signal = false;
public synchronized void take() {
this.signal = true;
this.notify();
}
public synchronized void release() throws InterruptedException {
while (!this.signal) wait();
this.signal = false;
}
}
Is it true, that by calling take() semaphore imitates signal acquisition and wakes up randomly chosen thread (if it actually exists) and by calling release(), if signal was not acquired, semaphore forces current(triggering) thread to wait for a notify() but sets signal acquisition to false?
And does it mean that, if I have single semaphore for 3 threads, I will have to run take() - release() pair for each thread in the part of code, which is not thread safe?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,正如所写,
take()
将从release()
中阻塞的线程中唤醒随机选择的线程,并且release()
将等待如果输入时signal
为 false,则调用take()
。这表明您的名称take()
和release()
向后:take()
应该是阻塞调用。这是一个二进制信号量,因为它只有两种状态。如果您像互斥锁一样使用它,那么您将需要一个
take()
-release()
对来包装需要隔离的代码。但是,在这种情况下,您最好使用普通的互斥体。信号量有很多用途(请参阅“信号量小书”),但通常比互斥体和监视器/条件变量更难正确使用。
Yes, as written,
take()
will wake a randomly chosen thread from those blocked inrelease()
, andrelease()
will wait for atake()
call ifsignal
is false on entry. This suggests that you have the namestake()
andrelease()
backwards:take()
should be the blocking call.This is a binary semaphore as it only has two states. If you use it like a mutex then you will need a
take()
-release()
pair wrapping the code that needs to be isolated. However, in that case you are better off with a plain mutex.Semaphores have many uses (see the "Little Book of Semaphores"), but are generally harder to use correctly than mutexes and monitors/condition variables.