C++ Have a function repeat in the background

2020-05-04 10:51发布

问题:

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.

回答1:

Use std::thread with this function:

#include <thread>

void foo() {
    // your code
}

int main() {
    std::thread thread(foo);
    thread.join();

    return 0;
}


回答2:

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:

double time_counter = 0;
clock_t this_time = clock();
clock_t last_time = this_time;
const int NUM_SECONDS = 1;
std::mutex protect; // <<<<
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);
            std::lock_guard<std::mutex> lock(protect); // <<<<
            rockSecPast++;
        }
    }
}

and do the same in your main thread

std::thread t(repeat);
t.detach();

// ....

int currentRockSecPast = 0;
{
    // read the asynchronously updated value safely
    std::lock_guard<std::mutex> lock(protect);
    currentRockSecPast = rockSecPast; 
}

If I were you I'd put all that mess from above together in a separate class.