Reputation: 707
Recently I have learned about multithreading library in c++11. I consider such a situation that there is a global variable int x=0 and there are two separate threads run in two separate cores. Whether the two threads may be write to memory of x simultaneously ? For example in thread#1 let x=0x0000, int thread#2 let x=0xffff, Could x be some invalidate value of 0x00ff ?
I have test it on x86-64 linux(windows) with g++ clang msvc, the answer is no, the value of x is 0x0000 or 0xffff. It looks like the assign operation is atomic or it just a coincidence.
Can someone help me about this?
Upvotes: 2
Views: 60
Reputation: 132994
Theoretically, speaking - you absolutely can end up with 0x00ff
, or even 0xabcd
. If two threads try to modify the value of an object, and these expressions are not sequenced (i.e. synchronized), the behavior of the program is undefined.
Now, whether or not this can happen in practice - it really depends on the OS and hardware architecture, and although the probability is low, it can still happen.
Use std::atomic<int>
instead of int
Upvotes: 2