Is it legal to initialize a Linux kernel semaphore with a negative number?

Let's say I want to wake up a task after the occurrence of n separate events. Is it legal to initialize a semaphore for 1 - n and down (), so I wake up after each of the events has up () 'd it?

+4
source share
3 answers

I do not think so.

(1) semephore.count is declared as unsigned int. See Definition of a semaphore:

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

(2) The down () function checks the count value before decreasing it; make sure that the count is not negative.

If you do not implement one mechanism, you cannot use the semaphore directly to fulfill your requirements.

+5
source

The counter is unsigned, so when you think you are setting it to a negative number, this is really a really big positive number. So no, you cannot.

+1
source

This is not a good idea, because it is unsigned. In addition, a semaphore is activated only when it is a positive number, so having a large number caused by initializing the semaphore with a negative number will cause your semaphore to allow access to what you want to restrict.

+1
source

Source: https://habr.com/ru/post/1494605/


All Articles