How does semaphore work?

后端 未结 6 1389
粉色の甜心
粉色の甜心 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:10

    Yes, a negative value means you have processes waiting for the semaphore to be released. A positive value means you can call acquire that many times before the semaphore blocks.

    You could think of the value in this way: a positive number means there are that many resources available. A negative value means there are that many entities needing a resource when all resources are taken at the moment. When you acquire a resource you decrement the value, when you release it you increase the value. If the value is still >= 0 after the decrement you get the resource, otherwise your entity is put into a queue.

    A nice explanation of semaphores in Wikipedia: http://en.wikipedia.org/wiki/Semaphore_(programming)

提交回复
热议问题