Delayed Function Call

﹥>﹥吖頭↗ 提交于 2020-01-01 19:58:22

问题


What's the most elegant way of performing a delayed (and therefore also asynchronous) functional call using C++11, lambdas and async? Suggested naming: delayed_async. Reason for asking is that I want a GUI alert light to be switched off after given time (in this case one second) without blocking the main (wxWidgets main loop) thread of course. I've use wxWidgets' wxTimer for this and I find wxTimer rather cumbersome to use in this case. So that got my curious about how much more convenient this could be implemented if I instead used C++11's async1, 2. I'm aware of that I need to protect the resources involved with mutexes, when using async.


回答1:


You mean something like this?

#include <iostream>
#include <chrono>
#include <thread>
#include <future>

int main()
{
    // Use async to launch a function (lambda) in parallel
    std::async(std::launch::async, [] () {
        // Use sleep_for to wait specified time (or sleep_until).
        std::this_thread::sleep_for( std::chrono::seconds{1});
        // Do whatever you want.
        std::cout << "Lights out!" << std::endl;
    } );
    std::this_thread::sleep_for( std::chrono::seconds{2});
    std::cout << "Finished" << std::endl;
}

Just make sure that you don't capture a variable by reference in the lambda.



来源:https://stackoverflow.com/questions/10804683/delayed-function-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!