Question 6725 – Image-Processing
November 27, 2023Question 16880 – Context-Free-Grammar
November 28, 2023Question 14246 – Semaphores
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.
- int counter = 0
- Semaphore S = init(5);
- void parop(void)
- {
- wait(S);
- wait(S);
- counter++;
- signal(S);
- signal(S);
- }
If five threads execute the function parop concurrently, which of the following program behaviour(s) is/are possible?
Correct Answer: C
count =0
S=5
func()
{
wait();
wait();
count++;
signal();
signal();
}
Answer:
(1) Deadlock is possible.
For a deadlock free operation
No. of resources >= No. of process (Req-1) + 1
Here, no. of resources = 5 (semaphore value)
Each thread requires = 2 resources (wait call)
No. of threads = 5
5 ≥ 5* (2-1)+1
≱ 6. So deadlock is possible.
This occurs when all 5 threads get blocked on first wait().
(2) count =5 is possible
When all threads enter CS and execute count++ sequentially.
(3) Count=1 is possible.
Assembly level:
read R0, count
inc R0, 1
write count, R0
Thread – 1 reads Count=0 in R0, preempted
Thread-2 reads count=0, is r1, completes, count=1
Thread-3, 4 & 5 completes.
Thread-1 is given CPU
MC R0, 1, so R0=1
Write R0 to count.
So, Count=1.