Semaphore mind blogging problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • lightsofamerica
    New Member
    • Jul 2008
    • 1

    Semaphore mind blogging problem

    Hi All,

    I am currently studying semaphores out of a book about multithreading. And one of the questions out of the book has got me stumped. The problem is we have bears and pengiuns who likes to swim. Each bear is a thread as is each pengiun. Bears and pengiuns both would liek to go into the pool and swim, but they both can't be in the pool at the same time. Bears can swim with other bears, and pengiuns can swim with other pengiuns. But bears can never swim with pengiuns.

    So I had some ideas on how to solve it, but it doesn't exactly work:

    1. If you are a pengiun, and you would like to swim, then you would go "down" on the semaphore (initialized to 1) and thus this will lock the pool. And then it can swim. Any other threads that try to go "down" on it will go to sleep because it is 0. This works because bears can't enter the pool. But it fails because pengiuns can't enter either. So essentially only one thread (bear or pengiun) can be in the pool at a given time.

    2. If you are a pengiun and you want to swim, you first increment the num_of_pengiun by 1, and then check if you are the first pengiun. If you are the first pengium, then you look the pool. Subsequent pengiuns who try to enter will also increment the num_of_pengiun by 1 and thus won't go "down" on the semaphore. And go directly to swim. Thus now we can be multiple pengiuns swimming.

    This almost works except if we duplicate the code for a bear, the first bear will increment the num_of_bear by 1, attempt to go down on the semaphore and go to sleep. But subsequent pairs will skip the down on semaphore code (because num_of_bear > 1) and thus go to swim directly. Again this fails.

    I can't think of a solution to this problem so I was wondering if anyone has any ideas?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    A single mutex (a binary semaphore) can do the job; think of that mutex as a
    gate to/from the pool. Both bears and penguins go through that gate (read: enter
    a critical section) and raise or lower their bear- or penguin-counter. Bears wait
    on the penguin-counter not being zero and penguins wait on the bear-counter
    not being zero. After they have woken up (read: went through the while-wait
    loop) they notify all the other sleeping animals.

    When an animal leaves the pool again, it enters the critical section again and
    lowers its counter and notifies all sleeping animals again. The critical section
    ensures that both the counters are only updated in a single thread.

    kind regards,

    Jos

    Comment

    Working...