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

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

问题描述

什么是执行延迟(因此也异步)使用C ++ 11 lambda表达式和异步功能调用的最优雅的方式?建议的命名: delayed_async 。理由,要求是,我想一个GUI警报光而不阻塞主(wxWidgets的主循环)当然螺纹关掉给定时间后(在此情况下,一秒钟)。我已经为这个使用wxWidgets的 wxTimer 我觉得 wxTimer 相当麻烦在这种情况下使用。这样得到了我的好奇如何方便多了,如果我改用C ++ 11的异步 1 ,的 2 。我意识到我需要保护涉及互斥的资源,使用时异步

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.

推荐答案

您的意思是这样?

#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天全站免登陆