Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 347
Lawrence D'Anna Avatar asked Jul 31 '13 23:07

Lawrence D'Anna


2 Answers

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.

like image 168
tian_yufeng Avatar answered Sep 28 '22 04:09

tian_yufeng


That is not a good idea because it is unsigned. Also, a semaphore is only activated when it is a positive number so having a large number caused by initializing the semaphore to a negative number will cause your semaphore to allow access to something that you would want to be restricted.

like image 40
P4T4R Avatar answered Sep 28 '22 05:09

P4T4R