I have some situations in a multithreaded app that I'm not sure about. I was hoping someone here might be able to answer these questions.
I know on older systems race conditions can be big trouble on older computers (I've written NES/SNES emulators, so I know that
very bad things can happen when different hardware attempts to access the same memory at the same time). However I would imagine that more modern computers are designed to cope with them better. So I'm wondering just how safe I need to be to guard against race conditions.
For the following examples, assume worst case scenarios (multi-core system, truely simultaneous accesses):
--------------------------------
1) A shared variable is
read by several threads, but is not written by any threads. Assuming the state of this variable never changes, is it safe to assume that all threads reading this variable will properly receive its contents? Or is it possible that a thread might receive garbage/open bus if it attempts to read while another thread is reading it?
Basically: do simultaneous read-only operations need to be guarded by mutexes?
--------------------------------
2) A shared variable is
written by only 1 thread, but is
read by several threads. Assuming this is a simple state change (assignment of a simple, basic data type -- no complex computations), will it be guaranteed that the reading threads will receive either the old
or new value? Example:
1 2 3 4 5 6 7 8 9 10 11
|
int shared = 0; // 0 initially
void WritingThread()
{
shared = 12345;
}
void ReadingThread()
{
int foo = shared;
}
|
Running this code, is it safe to assume that 'foo' will be either 0 or 12345? Or is another value possible due to a bus conflict / race condition / partially written value?
Thanks in advance for any help!