C++ Have a function repeat in the background

前端 未结 2 747
[愿得一人]
[愿得一人] 2021-01-27 18:21

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

相关标签:
2条回答
  • 2021-01-27 19:08

    Use std::thread with this function:

    #include <thread>
    
    void foo() {
        // your code
    }
    
    int main() {
        std::thread thread(foo);
        thread.join();
    
        return 0;
    }
    
    0 讨论(0)
  • 2021-01-27 19:25

    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.

    0 讨论(0)
提交回复
热议问题