Skip to content
GATEiit

GATE CSE 2021 Set 1 Q56: Possible outcomes of five threads with double wait on a semaphore

Question

Consider the following pseudocode, where S is a semaphore initialized to 5 in line#2 and counter is a shared variable initialized to 0 in line#1. Assume that the increment operation in line#7 is not atomic.

If five threads execute the function parop concurrently, which of the following program behavior(s) is/are possible?

1. int counter = 0;
2. Semaphore S = init(5);
3. void parop(void)
4. {
5.     wait(S);
6.     wait(S);
7.     counter++;
8.     signal(S);
9.     signal(S);
10.}

Try it: multiple select: one or more correct options

Select one or more options
Select all correct options. No negative marking, no partial marks.
Show answer and explanation

Answer: A, B, D (official GATE 2021 final answer key)

Concept used: With 5 permits and 2 needed per thread, up to 2 threads can be in the non-atomic increment together; if each thread grabs one permit first, all block.

First step: Consider the interleaving where all five threads finish line 5 before any reaches line 6; then consider two threads doing counter++ at the same time.

Full step-by-step solution

Detailed working, common mistakes and linked mock tests will be available with a free GATEiit account. Log-in is coming soon.

Share this question

WhatsAppDownload image

Source: official GATE 2021 Set 1 CS question paper and final answer key, organised by IIT Bombay. Question paper · Answer key