Is it safe to ignore the read-write race condition of a smoothly changing floating point value?

StackOverflow https://stackoverflow.com/questions/2340027

  •  22-09-2019
  •  | 
  •  

Question

While I try to put the animation update function and physics simulation of a game engine into a seperate thread for execution, I realize the potential race condition of some floating point values (say, position of an object) between the writer thread (animation,physics) and the reader thread (renderer) if both threads are going to access the values simultaneously.

My question is, given that even a floating point assignment is not atomic, will such a read-write race condition can result a wired/sudden change of the original smoothly changing values as seen by the reader?

Moreover, in my situation I can tolerance a small amount of error, since such error will not accumulate over the next rendering frame.

Was it helpful?

Solution

Theoretically speaking you could get a massive degree of error if there was a context switch between updating the exponent and updating the mantissa, but I doubt most platforms or architectures in use today allow such a thing to happen.

OTHER TIPS

For my understanding, you can ignore the race condition as long as you only have on thread writing the veriable at a time and you don't care if your reading thread(s) are not using the latest version.

From my understanding, writing the float should be atomic to your code, though this could be platform-dependent I assume.

Section 12.5 of ECMA-334 (the C# language specifcation) states:

Reads and writes of the following data types shall be atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.

To that end, you shouldn't see any corruption due to reads and writes of a float (assuming you don't mean double here, that is not guaranteed to be an atomic write).

However, what should be noted is that while the writing of the values is guaranteed to be atomic, the order of the reads/writes is not guaranteed unless you are using something specific, like a call to Monitor.Enter.

Monitor.Enter is a little heavy for this though, so I would recommend using the volatile keyword when declaring the variable. Assuming the read/write of this variable is the only thing that needs to occur, it will guarantee that the reads/writes are done in order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top