gpt4 book ai didi

c++11:如何在n秒后在主线程中执行一个函数

转载 作者:行者123 更新时间:2023-11-30 05:12:18 24 4
gpt4 key购买 nike

我需要在一定时间后停止游戏。 stop 方法必须在比方说一分钟后在主线程中运行。与此同时,玩家在玩,所以我无法停止执行。我试图理解线程和异步,但我开始认为它们在我的情况下都没有用(如果我加入,用户无法玩;如果我分离,将调用“停止”方法一个单独的线程)。我该如何处理?非常感谢

最佳答案

只要用 std::async 启动你的停止函数,然后在你的停止函数内部有一个 std::this_thread.sleep_for(60s) 作为第一次调用

例如

#include <future>
...
std::future<int> retCode = std::async(stop);
.. your game starts

int stop() 的内部

int stop()
{
std::this_thread::sleep_for(std::chrono::minute(1));
...do whatever to stop game...
}

关于c++11:如何在n秒后在主线程中执行一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44616241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com