I have read in many books and article aboutprotecting a critical section when two threads try to access the critical section simultaneously. Here atleast one threadmust bewriting to critical section (say a volatile integer variable int_X).We knowthat a non-atomiccritical section is not protected then behaviour is undefined. I want to know why the behaviour is undefined?
Iam curious to know what happens at the instruction (processor, cache)level when a 'Thread B' tries toread un-protected int_X and at the same time 'Thread A' isincrementingint_X? What happens when 'Thread A' isis halted by the processor when itsin mid of executing 'load','inc' and 'store'instruction to icrement int_X and then 'Thread B' is run which tries to read the value of int_X?
Thank you in advance.
Well, there's atomicity and there's volatility, which is not the same thing-- this blog from Arch Robison tries to make the differenceclear. Volatility affects the optimizations available to the compiler for improving performance of the code but has little meaning when referring to the interactions of a pair of HW threads within a multi-processor system. The questions raised above suggest that you might benefit from a little background reading on cache coherence.