views:

93

answers:

2

Possible Duplicate:
Can a C# thread really cache a value and ignore changes to that value on other threads?

Lets say we have this code:

bool KeepGoing = true;
DataInThread = new Thread(new ThreadStart(DataInThreadMethod));
DataInThread.Start();
//bla bla time goes on
KeepGoing = false;

private void DataInThreadMethod()
{
      while (KeepGoing)
      {
         //Do stuff
      }
   }
}

Now the idea is that using the boolean is a safe way to terminate the thread however because that boolean exists on the calling thread does that cause any issue?

That boolean is only used on the calling thread to stop the thread so its not like its being used elsewhere

+2  A: 

You need to clarify exactly what / where KeepGoing is, but no; it is not safe. It can be held in a register on x86 (but this is unlikely in most non-trivial examples). You need to make it volatile, or to synchronize (lock etc) access to it. For an example, see here.

Marc Gravell
KeepGoing is just a member/field in a program.
Jon
Is there an issue with x64 systems using volatile? I read this "With an x64 architecture this isn't optimized". What does that mean?
Jon
@Jon - Hard to answer that out-of-context, but I *assume* it means that maybe it won't be cached in the register. But IMO you should go for the code that *always* works.
Marc Gravell
The quote was in the comments of the accepted answer in the link you put in your answer
Jon
A: 

Hopefully I'm not going off on a tangent with this answer, but:

Jon's Worker class example has an alternative to what you're doing, which is thread safe. Two problem I've found with the while(boolVariable) approach is some tasks take longer than others (assuming you're performing more than one task) which means the stop isn't caught until the end of that task. The other is what happens when you get to the end of the loop? Break perhaps, or just repeat that task forever, which isn't always what you want if, for example, you're downloading a list of files.

Chris S