【发布时间】:2018-03-18 06:15:41
【问题描述】:
我正在用纯 c++11 编写,并且想要在关闭它之后执行一个简单的“等待 x 秒并打开一个成员变量”。本例中类的成员变量是“动画”的标志。
cout << "stop animating!" << endl;
this->animating = false;
async(launch::async, [this] ()
{
this_thread::sleep_for(chrono::seconds{8});
this->animating = true;
std::cout << "start animating!" << std::endl;
});
cout << "i'm here" << endl;
this_thread::sleep_for 会阻止整个程序继续运行(即使它位于异步线程中)。因为 8 秒后我没有看到“我在这里”。如果上面的代码按预期工作,我会在“停止动画”之后立即看到“我在这里”。这种阻塞对我来说是个问题,因为它会锁定我关心的所有内容,比如继续处理键盘事件等“输入”,并且程序还会停止在屏幕上“绘制”其他对象。
有谁知道如何使用标准 c++11 实现成员变量的简单延迟和异步更改(请不要使用 boost 之类的框架)
在 iOS 中非常简单:
// Delay execution of my block for 10 seconds.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC),
dispatch_get_main_queue(), ^
{
//do whatever, 10 seconds later
});
【问题讨论】:
-
要么改用
std::thread([this](){...}).detach();,要么尝试保存结果 std::future 并确保它不会超出范围。 -
是的。这似乎有效,甚至比跟踪从异步返回的自动未来更好。我想这就是答案
-
也许看看这个answer。正如 user2176127 提到的,你可以保存 std::future 否则它的析构函数会等待它的结果
标签: c++ c++11 asynchronous thread-sleep