C++ Have a function repeat in the background

前端 未结 2 776
[愿得一人]
[愿得一人] 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: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 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 lock(protect);
        currentRockSecPast = rockSecPast; 
    }
    

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

提交回复
热议问题