Machine-translated by Google. Questions are authored in English.
Top

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 ?

  • A.Reading array values
  • B.Add to tot_sum
  • C.Both (A) and (B)
  • D.Neither (A) nor (B)

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.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.