防止 sleep_for 阻塞后台线程

prevent sleep_for from blocking background thread

我正在用纯 c++11 编写,想在关闭它后做一个简单的 'wait x seconds and turn on a member variable'。本例中class的成员变量是'animating'.

的标志
        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 秒后我没有看到 "I'm here"。如果上面的代码按预期工作,我会在 "stop animating" 之后立即看到 "I'm here"。这种阻塞对我来说是个问题,因为它锁定了我关心的一切,比如继续处理 'input' 键盘事件,并且程序还会停止 'drawing' 屏幕上的其他对象。

有谁知道如何使用标准 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 无济于事。)