c - Multiple threads accessing one variable -


i found question in textbook reading. solution given below well. i'm having trouble understanding how minimum 2. why couldn't thread read 0, other threads execute , writes 1? , whether 1 or 2, thread writing last must still complete own loop?

int n = 0; int main(int argc, char **argv) {  (i = 0; < 5; i++) {  int tmp = n;  tmp = tmp + 1;  n = tmp;  }  return 0; } 

if single thread ran application, expect final output 5. if 5 threads ran same loop in parallel? largest , smallest values n have? largest should selfevident: 25, 5 increments 5 threads. however, reasoning smallest possible value more difficult. hint: n can less 5, figure out why.

solution:

with 5 threads running five-iteration loop , no protection concurrent accesses, lowest value n can reach two. understanding how reach result easiest when working backwards final result. final output two, thread must have read value of 1 n, incremented it, , written two. means thread wrote one, implying read 0 (which starting value n). accounts behavior of 2 of 5 threads. however, behavior occur results of other 3 threads must have been overwritten. 2 valid executions accomplish this. either 1) 3 threads began , completed execution between first thread reading 0 , writing one, or 2) 3 threads began , completed execution between final thread reading 1 , writing two. both execution orderings valid.

assuming every thread has local i (i.e., every thread run 5 iterations no matter what), let's try 1 result. mean last thread write value have read 0 n on 5th iteration. way happen if no thread has yet written n @ start of thread's 5th iteration, yet thread on 5th iteration thread must have written n, hence not possible.

thus smallest possible result 2, can occur, e.g., follows: last thread write n has completed 4 iterations, thread writes 1, last thread reads 1 @ start of 5th iteration, other threads complete iterations before last thread, , last thread completes 5th iteration writing 2.

disclaimer: answering conceptual question multithreading – others have pointed out, lack of atomicity might lead undefined behaviour , arbitrary results if c code presented used is. based on question's “self-evident” largest number case i'm guessing textbook's author either doesn't realise this, or using c-like pseudo code illustrate concept. if former, correct answer book wrong, think answer in latter case educational.


Comments