Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Confused about semaphores


    I am trying to allow a kernel thread to sleep while it waits for a buffered write to complete. Essentially I was trying:

    Created a:

    struct buffer_sem {
        struct list_head list;
        struct semaphore sem;
    That inits the semaphore with a value of 0.

    Then I add the semaphore to the "wait list" on the buffer itself and call:

    What is confusing me is: I thought that doing a "down" on a semaphore that is already at '0' would cause the semaphore to go to -1 and put the thread to sleep until a corresponding "up" is done. I put in a printk prior to the down and the up and what I'm seeing is that I can get 1, 2, 3, even 4 printk's from the down, followed by (because they each get added to the wait list - I assume) 1, 2, 3, even 4 up's.

    So why am I doing multiple downs? Did I set this up wrong?

    The behavior I want is for the "waiting" thread to sleep until the other thread has finished with the buffer. I would prefer to see only one down/up because multiple downs and ups would indicate that it's not actually sleeping, but it's looping, which is not what I want. Any suggestions?



  2. #2
    Sorry, forgot to mention...I keep track of the buffered writes by adding them to a list. The thread that should be sleeping is in a loop that checks the list for a matching buffer. To make sure that I didn't miss a buffer, after the down I reset to the beginning of the list and go through it again.

    So it looks like this:

    loop through list of writes
    if match:
      init semaphore to 0
      add semaphore to "wait" list on buffer
      down semaphore - I am expecting to sleep here, but it's not
      reset loop pointer to beginning of list
      continue loop
    The code the does the up is essentially:

    if waiters:
      loop through list of waiters
      remove semaphore from wait list
      up semaphore
    Again, what I'm confused about is why the down isn't causing the thread to go to sleep. Why does it seem to keep looping?



  3. #3
    Never mind...I figured out what was going on.

    The problem wasn't that down was behaving strangely, it's not, it was that multiple read requests for the same buffer are coming in at the same time. So everything is actually working as expected...sorry for the confusion, but I was confused



  4. $spacer_open

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts