Consider the following pseudocode, where is a semaphore initialized to in line and is a shared variable initialized to in line . Assume that the increment operation in line is atomic.
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. }
If five threads execute the function concurrently, which of the following program behavior(s) is/are possible?
View worked solution
Answer: A;B;D
Let us analyze each option by tracing the concurrent execution of the 5 threads:
- Option D is possible (Deadlock):
Initially, . Suppose all 5 threads execute their first
wait(S)statement (line 5) concurrently. Each thread successfully decrements by 1, making . Now, all 5 threads reach line 6 and attempt to execute the secondwait(S). Since , all of them block indefinitely, resulting in a deadlock. - Option A is possible (Value of 5):
If the threads execute sequentially one after another without any interleaved context switches during the non-atomic
counter++operation, each thread successfully increments thecounterby 1. The final value ofcounterwill be . - Option B is possible (Value of 1):
Since the
counter++operation is non-atomic, it consists of three steps: Read, Increment, and Write.- Thread enters the critical section, reads
counter = 0into its local register, and is preempted before writing. - Since holds 2 units of the semaphore, . The remaining threads can still execute sequentially. They run to completion, updating
counterto . - Thread resumes, increments its local register value from to , and writes back to
counter.
counterbecomes . - Thread enters the critical section, reads
- Option C is impossible (Value of 0):
If all threads successfully complete their execution, at least one write operation to
countermust occur. Sincecounterstarts at and any write operation writes a value of at least , the final value ofcountercan never be .
Free practice · Your answers on this page are not saved.
