Is it legal to initialize a linux kernel semaphore to a negative number?

linux, linux-kernel

Solution

I don't think so.

(1) The semephore.count is declared as unsigned int. See semaphore definition:

    struct semaphore {
        spinlock_t      lock;
        unsigned int        count;
        struct list_head    wait_list;
    };

(2) The down() function will check the count value before decrease it, make sure the count is not negative.

Unless you implement one mechanism, you can not use semaphore directly to accomplish your requirement.

Problem

Say I want to wake up a task after n separate events have occurred. Is it legal to initialize a semaphore to 1 - n, and down() it, so I wake up after each of the events have up()'d it?

Original source