延迟函数调用 [英] Delayed Function Call

查看:130
本文介绍了延迟函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C ++ 11,lambdas和async执行延迟(因此也是异步)函数调用的最优雅的方法是什么?建议命名: delayed_async 。要求的原因是,我想要一个GUI警报灯在给定时间后(在这种情况下一秒钟),而不阻塞主(wxWidgets主循环)线程当然。我使用wxWidgets的 wxTimer 这个,我发现 wxTimer 在这种情况下使用比较麻烦。所以这让我很好奇,如果我改用C ++ 11的 async 1 2 。我知道当使用 async 时,我需要保护涉及互斥体的资源。

解决



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

int main()
{
//使用异步并行启动函数(lambda)
std :: async(std :: launch :: async ,[](){
//使用sleep_for等待指定的时间(或sleep_until)
std :: this_thread :: sleep_for(std :: chrono :: seconds {1});
//做任何你想要的。
std :: cout<<Lights out!<< std :: endl;
});
std :: this_thread :: sleep_for(std :: chrono :: seconds {2});
std :: cout<< 完成<< std :: endl;
}

只需确保您不在lambda中捕获引用的变量。


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.

解决方案

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.

这篇关于延迟函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆