ronag
ronag

Reputation: 51263

Is atomic CAS required when setting a boolean to true

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_;
};

Upvotes: 1

Views: 1079

Answers (1)

JustBoo
JustBoo

Reputation: 1741

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

Upvotes: 3

Related Questions