简体   繁体   English

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

[英]Call a function after x seconds while keep running rest of the program in C++

我有一个程序,我想在 x 秒或分钟后调用一个函数,同时继续运行程序的其余部分。

You should run new thread:您应该运行新线程:

#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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM