views:

57

answers:

3

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.

+1  A: 

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.

Romain
+1  A: 

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.

casperOne
A: 

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.

Kylotan
You are only speaking about the one cpu case 'context switching' between multiple threads. On a shared memory architecture, like PC or xbox360, multiple threads on different cpu's can simultaneously access the same memory.
Evan Rogers
I was talking about any modern platform. I would be somewhat surprised if it were possible to read a floating point value in the middle of it being physically written. I expect the bus or the cache or *something* will be locked during that process so that the instruction completes correctly. But further evidence either way would be useful.
Kylotan