阻止sleep_for阻止后台线程

时间:2018-03-17 18:24:38

标签: c++ c++11 asynchronous thread-sleep

我在纯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 会阻止整个程序继续运行(即使它位于异步线程内)。因为我没有看到&#34;我在这里&#34; 8秒后如果上面的代码按预期工作,我会看到&#34;我在这里&#34;紧接着#34;停止制作动画&#34;。这种阻塞对我来说是一个问题,因为它会锁定我关心的所有内容,例如继续处理&#39;输入&#39;像键盘事件一样,程序也会停止绘制&#39;屏幕上的其他对象。

有没有人知道如何使用标准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
});

1 个答案:

答案 0 :(得分:3)

根据@ 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无法帮助。)

相关问题