C ++在后台重复执行功能 [英] C++ Have a function repeat in the background

查看:115
本文介绍了C ++在后台重复执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Microsoft Visual Express.

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.

我也做了一些Google搜索,发现大部分重复操作仅在运行该功能时才重复,而在其他功能中却没有继续.

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.

推荐答案

将此功能与std::thread一起使用:

#include <thread>

void foo() {
    // your code
}

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

    return 0;
}

这篇关于C ++在后台重复执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆