6

What is semaphore.... My brain refuses to understand.

Comments
  • 3
    Basically you lock a certain area of code for other threads and processes to avoid conflicts.
    When the semaphore is left then a waiting thread gets waken
  • 3
    Better example
    Have you been waiting out a bathroom?
    And the bathroom can contain only one person?
    When the first guys leaves the bathroom you enter
    And when you leave the one next in the queue of waiting people enters
    And so....
  • 7
    Semaphore means traffic light in my language so maybe that helps to understand?
  • 2
    Related: dining philosophers problem
  • 4
    There are 2 beer taps and more guys wanting to get beers. The semaphore is 0. Maximum value is 2 because only two beer resources (taps) can be used at the same time.

    The first guy orders. Semaphore is incremented, now it's 1. One of the taps starts pouring beer.

    Second guy orders. Semaphore is incremented, now it's 2, other tap starts releasing beer too.

    Third pal orders. Semaphore is 2 so can't be incremented, his request is blocking until one of the taps releases the required beer and the beer pouring resource is freed up.

    When one of the taps finished pouring beer, we decrement the semaphore by 1, now it's 1 again, so a tap can be allocated again.

    Basically using a semaphore like this in a pub means that no bartender can use the same tap for two different pints at the same time.
Add Comment