Computer Sciences > Gate 2024 Set-2 > Thread
Consider a multi-threaded program with two threads T1 and T2. The threads share two semaphores: s1 (initialized to 1) and s2 (initialized to 0). The threads also share a global variable x (initialized to 0). The threads execute the code shown below.
Which of the following outcomes is/are possible when threads T1 and T2 execute concurrently?
A
T1 runs first and prints 1, T2 runs next and prints 2
B
T2 runs first and prints 1, T1 runs next and prints 2
C
T1 runs first and prints 1, T2 does not print anything (deadlock)
D
T2 runs first and prints 1, T1 does not print anything (deadlock)

Correct : b,c

Explanation:
Let us analyze the possible execution sequences of threads T1 and T2 based on which thread acquires the shared semaphore s1 (initialized to 1) first.
Case 1: T1 executes first 1. T1 executes wait(s1) successfully (s1 becomes 0). 2. T1 increments x to 1 and prints 1. 3. T1 executes wait(s2). Since s2 = 0, T1 blocks here. 4. If a context switch occurs, T2 tries to execute wait(s1). Since s1 = 0, T2 also blocks.
Both threads are permanently blocked waiting for each other, resulting in a deadlock where only 1 was printed.
This validates Option (c).
Case 2: T2 executes first 1. T2 executes wait(s1) successfully (s1 becomes 0). 2. T2 increments x to 1 and prints 1. 3. T2 signals s2 (s2 = 1) and signals s1 (s1 = 1), completing its execution. 4. T1 is now free to run. It passes wait(s1), increments x to 2, and prints 2. 5. T1 passes wait(s2) without blocking because s2 was set to 1 by T2.
Both threads finish successfully, printing 1 followed by 2.
This validates Option (b).
Conclusion: The possible outcomes are b and c.

Similar Questions

Consider the following expression: π‘₯[𝑖]=(𝑝+π‘Ÿ)βˆ—βˆ’π‘ [𝑖]+𝑒/𝑀. The following sequence shows the list of triples representing the given expression, with entries mi...
#843 MCQ
Consider an array X that contains n positive integers. A subarray of X is defined to be a sequence of array locations with consecutive indices. The C code...
#844 MCQ
Let 𝑀 be the 5-state NFA with πœ–-transitions shown in the diagram below. Which one of the following regular expressions represents the language accepted...
#845 MCQ

Related Topics

No tags found

Unique Visitor Count

Total Unique Visitors

Loading......