视觉工作室 - C++ 在后台重复一个功能

visual studio - C++ Have a function repeat in the background

本文关键字:功能 一个 工作室 C++ 后台 视觉      更新时间:2023-10-16

我正在使用Microsoft Visual Express。

我已经查看了这个问题的已接受答案,它似乎没有做我想要它做的事情。

这是我每秒重复一次的功能:

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++;
        }
    }
}

我试图完成的是,在后台重复这一点。我的意思是我希望这个函数运行,但程序仍然继续其他函数并正常运行,这个函数总是在后台重复。

我尝试的是查看这个问题以寻找答案。但是我没有找到。

的问题:我如何在后台重复一个函数,而程序仍然可以继续并与其他函数一起正常运行。一切应该仍然有效,但函数应始终在后台运行。

我也做了一些谷歌搜索,我发现的大部分内容都是连续重复,只运行该功能,而不继续其他功能。

std::thread与以下函数一起使用:

#include <thread>
void foo() {
    // your code
}
int main() {
    std::thread thread(foo);
    thread.join();
    return 0;
}

你想要的是我在评论中提到的std::thread。但也要注意,您需要一种同步机制来防止全局变量的并发访问:

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++;
        }
    }
}

并在您的主线程中执行相同的操作

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

如果我是你,我会把上面所有的混乱放在一个单独的班级里。

相关文章: