1

I have class where a bool is access concurrently. However in my case it is only initialized to false once in the constructor, and after that it set to false. Am i correct to believe that even though a race might occur the result will be valid and defined? Since the entire bool doesn't have to be written to inorder for "!isStopping_" to evaluate to true.

class MyClass
{
public:
   MyClass() : isStopping_(false), thread_([=]{Run();}) {}

   void Stop()
   {
      isStopping_ = true;
   }

private:

   void Run()
   {
       while(!isStopping_) // data race
       {
            // Work
       }
   } 

   bool isStopping_ ;
   boost::thread thread_;
};
ronag
  • 49,529
  • 25
  • 126
  • 221
  • 2
    As long as the cache doesn't prevent not-reading-new-values then it should be fine. Only one bit needs to be set (even if the write itself is not atomic across all words) -- and it's only ever set one way while in a "shared" state. **Better mark it volatile (for the cache/access issues).** –  Aug 06 '10 at 17:56
  • Yeah, questions about volatile v. MT asked here pretty much every day. Recent one: http://stackoverflow.com/questions/3372703/volatile-and-multithreading – Dummy00001 Aug 06 '10 at 23:31

1 Answers1

3

I'm not quite sure of the question, but you should probably look into the "volatile" keyword. IIRC, it insures the value is updated whenever accessed.

http://en.wikipedia.org/wiki/Volatile_variable

HTH

JustBoo
  • 1,723
  • 9
  • 9