I had a problem with starting and stopping background threads based on the value of a boolean flag. I had asked for help here and got a very detailed answer here.
However, after using the solution for a few days, it seems to me that there is something wrong with it. I launch a worker thread in SomeObject::DoRun called in SomeObject::Start which should do some work in a loop and quit when I call SomeObject::Stop:
struct SomeObject {
SomeObject() { SetDone(true); }
std::atomic_bool done_;
void DoRun();
void SetDone(bool v) { done_store(v); }
bool IsDone() { return done_.load(); }
void Start() {
if (IsDone()) {
SetDone(false);
DoRun();
}
void Stop() { SetDone(true); }
};
However, it seems like sometimes the check for IsDone() in Start() returns false and DoRun() never gets called even though I have set done to true in the constructor.
The reason I set done_ to true in constructor and then set it to false in Start() is that I want to call Start()/Stop() repeatedly on the same object.
What am I doing wrong here?