Theoretically, thread-safe code should fix race conditions. Race conditions, as I understand it, occur because two threads attempt to write to the same location at the same time.
However, what about a threading model in which a single thread is designed to write to a location, and several slave/worker threads simply read from the location?
Assuming the value/timing at which they read the data isn’t relevant/doesn’t hinder the worker thread’s outcome, wouldn’t this be considered ‘thread safe’, or am I missing something in my logic?
1
There are two problems:
- If there is more than a single value being written, then without synchronization the reading threads could see partially written and thus inconsistent data. Even single values could be read in a partially written state that corresponds to none of the legitimate values (e.g. in Java, writing to double and long fields is not guaranteed to be atomic).
- Reading threads could get outdated values for an arbitrarily long time after it’s been written, due to caching. If that’s not a problem, why have a writing thread at all?
6
There are more problems than that.
-
write may not be atomic, that is a thread could see a partially updated value
-
even if all writes are atomic, you may get in the situation where you write A then B but another thread see the new B and the old A. You need some synchronizations instructions to ensure that you see everything that you want. Those instructions may be needed in both threads, not just the writer or the reader one.
0