Consider a multi-threaded program with two threads T1 and T2 sharing semaphores s1 (initialized to 1) and s2 (initialized to 0) and a global variable x (initialized to 0). T1: wait(s1); x = x+1; print(x); wait(s2); signal(s1). T2: wait(s1); x = x+1; print(x); signal(s2); signal(s1). Which of the following outcomes is/are possible when threads T1 and T2 execute concurrently?
T1 runs first and prints 1, T2 runs next and prints 2
T2 runs first and prints 1, T1 runs next and prints 2
T1 runs first and prints 1, T2 does not print anything (deadlock)
T2 runs first and prints 1, T1 does not print anything (deadlock)
Correct answer: (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)
Explanation
If T1 goes first it holds s1 and blocks on wait(s2), which only T2 can signal, but T2 is blocked on s1: deadlock (C). If T2 goes first it prints 1, signals s2 and s1, then T1 runs and prints 2 (B). A is impossible and D cannot deadlock.
More Concurrency and Synchronization questions
GATE 2023 CS Q38– Consider the two functions incr and decr shown below. There are 5 threads each invoking…
GATE 2022 CS Q19– Consider the following threads, T1, T2, and T3 executing on a single processor,…
GATE 2021 CS (CS1) Q56– Consider the following pseudocode, where S is a semaphore initialized to 5 in line#2 and…
GATE 2020 CS Q44– Each of a set of n processes executes the following code using two semaphores a and b…
GATE 2019 CS Q33– Consider three concurrent processes P1, P2 and P3 as shown below, which access a shared…
GATE 2018 CS Q50– Consider the following solution to the producer-consumer synchronization problem. The…