A counting semaphore was initialized to 8. Then 12 P (wait) operations and 7 V…

2022

A counting semaphore was initialized to 8. Then 12 P (wait) operations and 7 V (signal) operations were completed on this semaphore. The resulting value of semaphore is –

Answer: B. 3Concept A counting semaphore is an integer counter guarded by two atomic operations. P (wait, from the Dutch Proberen) subtracts 1 from the counter; V…

  1. A.

    4

  2. B.

    3

  3. C.

    5

  4. D.

    1

Attempted by 618 students.

Show answer & explanation

Correct answer: B

Concept

A counting semaphore is an integer counter guarded by two atomic operations. P (wait, from the Dutch Proberen) subtracts 1 from the counter; V (signal, from Verhogen) adds 1 to it. In the counting-semaphore model the counter is not clamped at zero: a positive value counts the resource units still free, while a negative value counts the processes currently queued on it. Because each operation changes the counter by exactly one unit, the final value depends only on the starting value and on how many operations of each kind completed, never on the order in which they ran.

Applying it to this semaphore

  1. Starting value of the counter: S = 8.

  2. 12 P (wait) operations complete, each subtracting 1, contributing -12.

  3. 7 V (signal) operations complete, each adding 1, contributing +7.

  4. Assemble the running total: S = 8 - 12 + 7.

  5. 8 - 12 = -4, and -4 + 7 = 3.

Cross-check: the never-below-zero implementation reaches the same total

A frequent objection is that wait() spins while the counter is 0 and therefore can never drive it negative, so the count would sit at 8 - 8 = 0 after the first eight waits and then climb to 0 + 7 = 7. Trace that implementation through to the end. The first eight waits find a positive counter, pass through, and leave it at 0. The remaining four waits block. Each of the 7 signals then adds 1, and the first four of those increments are taken immediately by the four blocked waits as they are released. Four increments are consumed, three are left, and the counter settles at 3. The two implementations differ only in bookkeeping, recording the four pending waits either as a counter of -4 or as four processes in the queue, and the question states that all 12 wait operations were completed, so both reach 3.

Implementation

How the four pending waits are recorded

Counter after all 12 waits and all 7 signals have completed

Counter may go negative

As a counter value of -4

3

Counter clamped at 0; those waits block

As four processes waiting in the queue

3

Contrast

This arithmetic is specific to a counting semaphore. A binary semaphore holds only 0 or 1, so repeated signal operations cannot accumulate on it and the running total above does not apply.

Resulting value of the semaphore: 3.

Explore the full course: Up Lt Grade Assistant Teacher 2025

Loading lesson…