C++每 x 秒调用一次函数
C++ call a function every x seconds
我试图每 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
函数中,了解每个线程在做什么很重要。
- 主线程创建一个名为
t1
的std::thread
- 主线程继续并分离线程
- 主线程执行您的
while
循环,其中:- 打印你好
- 睡眠 0.5 秒
- 主线程返回 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;
}
相关文章:
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 如何为非常量和常量重载实现一次成员函数?
- 某些 boost::asio 异步函数是否将处理程序连接到操作,以便处理程序被触发一次?
- 如何一次运行3个函数?
- 循环中本地对象的析构函数是否保证在下一次迭代之前被调用?
- 调用函数一次用于动态链接库,一次从可执行文件调用函数
- 仅在函数中设置静态变量一次
- 有没有办法一次运行 3 个创建窗口函数?
- 在可变函数调用中执行一次语句
- 为什么转换运算符调用复制构造函数两次,而等效函数只调用它一次
- 为什么一次包装 typedef 函数签名与原始签名不匹配
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- 我需要线程函数在不停止实际程序的情况下,每2秒打印一次随机数
- Android JNI RegisterNatives:对所有内容调用一次,或者每个函数调用一次
- 如何在 constexpr 构造函数中初始化矩阵一次?
- cppUnit:针对多个测试方法执行一次的设置函数
- 为什么调用 cout.operator<<(const char*) 打印地址而不是字符串? 如何创建一个函数本地静态"HashSet<char>"并初始化它一次?
- 跨类的多个实例调用函数一次
- C++一次将函数标记为静态就足够了?