我正在用纯 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
});
最佳答案
根据@user2176127的评论 - 你尝试过这个吗? :
cout << "stop animating!" << endl;
this->animating = false;
std::thread delay_thread(
[this]() {
this_thread::sleep_for(chrono::seconds{8});
this->animating = true;
std::cout << "start animating!" << std::endl;
}
);
delay_thread.detach();
std::cout << "I'm here" << std::endl;
另请注意,您可能需要包装 animating
std::atomic<>
中的成员,即如果是 bool
它现在变成了std::atomic<bool>
,以确保您的主线程在实际发生时注意到更改。 (使用 volatile
没有帮助。)
关于c++ - 防止 sleep_for 阻塞后台线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49340384/