在 x 秒后调用一个函数,同时在 C++ 中保留 运行 程序的其余部分

Call a function after x seconds while keep running rest of the program in 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();
}