C++每 x 秒调用一次函数

C++ call a function every x seconds

本文关键字:一次 函数 调用 C++      更新时间:2023-10-16

我试图每 5 秒运行一次 run(( 函数而不停止 while(( 循环(并行(。我该怎么做?提前致谢

#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
void run() 
{
this_thread::sleep_for(chrono::milliseconds(5000));
cout << "good morning" << endl;
}

int main()
{
thread t1(run);
t1.detach();
while(1)
{
cout << "hello" << endl;
this_thread::sleep_for(chrono::milliseconds(500));
}
return 0;
}

main函数中,了解每个线程在做什么很重要。

  1. 主线程创建一个名为t1std::thread
  2. 主线程继续并分离线程
  3. 主线程执行您的while循环,其中:
    • 打印你好
    • 睡眠 0.5 秒
  4. 主线程返回 0,您的程序已完成。

从第 1 点开始的任何时间,线程t1休眠 5 秒,然后打印早安。这种情况只发生一次!此外,正如@Fareanor所指出的,std::cout不是线程安全的,因此使用主线程和线程t1访问它可能会导致数据争用。

当主线程到达第 4 点时(实际上永远不会这样做,因为您的while循环是无限的(,您的线程t1可能已经完成了它的任务。 想象一下可能发生的潜在问题。在大多数情况下,您需要使用std::thread::join().

要解决您的问题,有几种选择。在下文中,我们将假设根据@Landstalker的评论,与 5 秒相比,没有std::this_thread::sleep_for的函数run的执行微不足道。然后,run的执行时间为 5 秒加上一些微不足道的时间。

如注释中所建议的,您可以通过在该函数内放置一个while循环来简单地每 5 秒执行一次run体,而不是每 5 秒执行一次函数run一次:

void run() 
{
while (true)
{
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << "good morning" << std::endl;
}
}
int main()
{
std::thread t(run);
t.join();
return 0;
}

如果出于某种原因,您确实需要每 5 秒执行一次run函数,如您的问题中所述,您可以启动包含while循环的包装器函数或 lambda:

void run() 
{
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::cout << "good morning" << std::endl;
}
int main()
{
auto exec_run = [](){ while (true) run(); };
std::thread t(exec_run);
t.join();
return 0;
}

作为旁注,最好避免using namespace std.

只需在单独的线程函数中调用您的 run 函数,如下所示。这对你来说可以吗?

void ThreadFunction()
{
while(true) {
run();
this_thread::sleep_for(chrono::milliseconds(5000));
}
}
void run() 
{
cout << "good morning" << endl;
}

int main()
{
thread t1(ThreadFunction);
t1.detach();
while(1)
{
cout << "hello" << endl;
this_thread::sleep_for(chrono::milliseconds(500));
}
return 0;
}
相关文章: