Two threads accesses a shared int, x
. What problems can arise from instruction reordering etc.
Without mutexes? Don't do that or you'll be risking nasal demons. :-) To be exact, anything can happen. It might even appear to work (as long as you're not relying on consistent values). But really don't do that.
What would change if x
is declarared volatile
?
Not much, or maybe the behaviour would be different but you'd still not get things like you'd want. Volatile variables are for handling things like memory-mapped devices, not tricking your way past CPU caches.
What would change if Thread 1 and Thread 2 runs on different cores?
The problems would get worse (and yet you might not see any differences immediately either). Without a mutex or semaphore, you won't be using any memory barriers; they're the key to making things work (along with a proper lock to stop one thread from reading or writing when the other is writing) and they're not at all part of standard C++. That's why you use proper thread primitives; they solve these awkward problems for you.
Be aware that testing is not guaranteed to pick up thread consistency problems; they're inherently close to race conditions, and what happens will often change depending on system load.