I am using microsoft visual express.
I have viewed the accepted answer for this question and it seems to not be doing what I want it to do.
This is the function that repeats every second for me:
double time_counter = 0;
clock_t this_time = clock();
clock_t last_time = this_time;
const int NUM_SECONDS = 1;
void repeat()
{
while (1)
{
this_time = clock();
time_counter += (double)(this_time - last_time);
last_time = this_time;
if (time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC))
{
time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
rockSecPast++;
}
}
}
What I am trying to accomplish is repeating this while in the background. What I mean by this is I want this function to run, but the program still go on to other functions and run normally with this function always repeating in the background.
What I have tried is viewing that question for an answer. However I did not find one.
My question: How would I have a function repeat in the background, while the program can still continue and run normally with other functions. Everything should still work, but the function should always run in the background.
I have also done some google searching and most of what I find is repeating continuously only running that function and not continuing to other functions.
What you want is a
std::thread
as I mentioned in my comment. But also note you need a synchronization mechanism to prevent concurrent access for your global variables:and do the same in your main thread
If I were you I'd put all that mess from above together in a separate class.
Use
std::thread
with this function: