如何解释信号量处理操作?

发布于 2024-09-25 15:11:18 字数 516 浏览 4 评论 0原文

接下来是一个简单的信号量实现。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

水溶 2024-10-02 15:11:18

是的,正如所写,take() 将从 release() 中阻塞的线程中唤醒随机选择的线程,并且 release() 将等待如果输入时 signal 为 false,则调用 take()。这表明您的名称 take()release() 向后:take() 应该是阻塞调用。

这是一个二进制信号量,因为它只有两种状态。如果您像互斥锁一样使用它,那么您将需要一个 take() - release() 对来包装需要隔离的代码。但是,在这种情况下,您最好使用普通的互斥体。

信号量有很多用途(请参阅“信号量小书”),但通常比互斥体和监视器/条件变量更难正确使用。

Yes, as written, take() will wake a randomly chosen thread from those blocked in release(), and release() will wait for a take() call if signal is false on entry. This suggests that you have the names take() and release() 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文