Discussion
Consider a program, which spawn 20 threads to find out the sum of elements in a shared array of 200. Each thread i, takes elements A[i] to A[(20 * i) - 1] and compute local sum loc_sum [i] and eventually adds loc_sum[i] to a shared variable tot_sum for total sum which of the following needs to be placed inside a critical section ?
Answer: B
Only adding to tot_sum must be in a critical section.
All threads update the shared variable tot_sum, and each update is a read-modify-write: read the total, add the local sum, write it back. If two threads interleave these steps, one update can be lost, so the addition must be protected by a lock or made atomic.
Reading the array values needs no protection because the threads only read the shared array and nobody writes to it while they run; each thread builds its own loc_sum. So neither 'reading array values' nor 'both' is needed, and 'neither' would allow lost updates.
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