I have some code that will be accessed from two threads:
class Timer{
public:
void Start(){
start_ = clock_->GetCurrentTime();
running_ = true;
}
void Read(){
if(running_){
time_duration remaining = clock_->GetCurrentTime() - start_;
Actions(remaining)
}
}
private:
void Actions(time_duration remaining);
time start_;
bool running;
};
I've looked at some other timers available in various libraries, but didn't find any that fit my requirements, thus I'm rolling my own...
The Start() method is called (once only) from one thread. The Read() method is called very rapidly from another thread, the calls will start coming in before Start() is called.
Obviously it is very important that the start_ variable is initialized before the running_ flag is set. This could be solved by adding a mutex that gets grabbed when the Start() method is entered...and is grabbed before running_ is checked in the Read() method...but it seems somewhat unnecessary. If everything here executes in order, then there are no problems. I have no problem with the fact that a Read() could happen while the other thread is in the Start() routing, getting the time from the clock for example...the Read()s happen fast enough that its just not a big deal.
Anyway, I was looking for a way to ensure that the compiler/processor will execute the
start_ = clock_->GetCurrentTime();
running_ = true;
instructions in order they are listed above. (Or if I'm overlooking something else).