Well, there is a clear race condition that they could see done as false and execute the if body - this is true, regardless of the memory model. Running done volatile will not fix this, and it will not fix it in Java either.
But yes, it is possible that changes made in one thread may occur, but will not be visible until in another thread. It depends on the processor architecture, etc. As an example of what I mean, consider this program:
using System; using System.Threading; class Test { private bool stop = false; static void Main() { new Test().Start(); } void Start() { new Thread(ThreadJob).Start(); Thread.Sleep(500); stop = true; } void ThreadJob() { int x = 0; while (!stop) { x++; } Console.WriteLine("Counted to {0}", x); } }
While this ends on my current laptop, I used other machines where pretty much the same code would work forever — it would never “see” the change to stop in the second thread.
Basically, I try to avoid writing code without blocking, unless it uses the higher-level abstractions provided by people who really know their stuff - for example, Parallel Extensions in .NET 4.
There is a way to make this code open and correct using Interlocked . For instance:
class ThreadTest { int done; static void Main() { ThreadTest tt = new ThreadTest();
Here, the value change and its testing are performed as a whole: CompareExchange will set the value to only 1 if it is currently 0, and will return the old value. Thus, only one thread will ever see the return value of 0.
One more thing to keep in mind: your question is rather ambiguous, as you have not defined what you mean by “streaming security”. I guessed about your intentions, but you never made it clear. Read this Eric Lippert blog post - it's worth it.