问题描述
我有一个程序,我想在 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();
}