Discussion
Consider the following two threads T1 and T2 that update two shared variables a and b. Assume that initially a = b = 1. Though context switching between threads can happen at any time, each statement of T1 or T2 is executed atomically without interruption.
T1:a = a + 1;
b = b + 1;
T2:b = 2 * b;
a = 2 * a;
Which one of the following options lists all the possible combinations of values of a and b after both T1 and T2 finish execution?
Answer: A
The possible results are (a = 4, b = 4); (a = 3, b = 3); (a = 4, b = 3).
Each thread's two statements run in order, giving six interleavings. What matters is whether each update to a comes before or after the other thread's update to a, and the same for b:
- a: a + 1 then 2a gives 4; 2a then a + 1 gives 3.
- b: b + 1 then 2b gives 4; 2b then b + 1 gives 3.
T1 updates a before b and T2 updates b before a. If T1's a-update comes after T2's a-update, T2 has already finished, so T1's b-update is also last: (3, 3). Otherwise a = 4 and b can be either. So (4, 4), (4, 3) and (3, 3) occur, but (3, 4) cannot, which rules out options B and C. Values of 2 would require an update to be lost, impossible with atomic statements.
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development