How does semaphore work?

后端 未结 6 1387
粉色の甜心
粉色の甜心 2021-02-04 07:44

Can the semaphore be lower than 0? I mean, say I have a semaphore with N=3 and I call \"down\" 4 times, then N will remain 0 but one process will be blocked?

And same th

6条回答
  •  孤独总比滥情好
    2021-02-04 08:06

    (Using the terminology from java.util.concurrent.Semaphore given the Java tag. Some of these details are implementation-specific. I suspect your "down" is the Java semaphore's acquire() method, and your "up" is release().)

    Yes, your last call to acquire() will block until another thread calls release() or your thread is interrupted.

    Yes, you can call release() more times, then down more times - at least with java.util.concurrent.Semaphore.

    Some other implementations of a semaphore may have an idea of a "maximum" number of permits, and a call to release beyond that maximum would fail. The Java Semaphore class allows a reverse situation, where a semaphore can start off with a negative number of permits, and all acquire() calls will fail until there have been enough release() calls. Once the number of permits has become non-negative, it will never become negative again.

提交回复
热议问题