How to explain semaphore processing operation?

主宰稳场 提交于 2020-01-07 04:10:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/3826088/how-to-explain-semaphore-processing-operation

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