如何解决x 秒后调用一个函数,同时继续在 C++ 中运行程序的其余部分
我有一个程序,我想在 x 秒或分钟后调用一个函数,同时继续运行程序的其余部分。
解决方法
您应该运行新线程:
#include <string>
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
// The function we want to execute on the new thread.
void task(int sleep)
{
std::this_thread::sleep_for (std::chrono::seconds(sleep));
cout << "print after " << sleep << " seconds" << endl;
}
int main()
{
// Constructs the new thread and runs it. Does not block execution.
thread t1(task,5);
// Do other things...
// Makes the main thread wait for the new thread to finish execution,therefore blocks its own execution.
t1.join();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。