AbhinavChoudhury
AbhinavChoudhury

Reputation: 1187

Counting semaphores initialized to n

If a counting semaphore is initialized to n, does it mean n processes can run their critical sections concurrently?

Upvotes: 1

Views: 1497

Answers (3)

Sushil Lakra
Sushil Lakra

Reputation: 67

Yes, if you have initialized semaphore to N, then sem_wait will not block any thread unless it has already been called N times, then only semaphore becomes -ve and that's when any thread calling sem_wait blocks.

for critical section you have to use binary semaphores or mutex.

Upvotes: 0

Sparky
Sparky

Reputation: 14057

No.

If n > 0, then it means that the counting semaphore can be taken exactly n times before the requesting context blocks and waits for the counting semaphore to become available (assuming no one gives it during that period).

If n <= 0, then it means that that counting semaphore must be given (1 - n) times before anyone can successfully take that counting semaphore.

Controlling access to a critical section is typically better handled by a mutex.

Upvotes: 1

aaaaaa123456789
aaaaaa123456789

Reputation: 5842

Essentially, yes.

Remember a counting semaphore will only block when the count is negative after decrementing. Therefore, the semaphore can be decremented n times before blocking. Since all decrements must be matched with an increment, then, assuming each process decrements the semaphore only once (which is, by far, the most common case), then yes, n processes will be able to run their critical sections at the same time.

Upvotes: 2

Related Questions