Nor*_*löw 0 c++ asynchronous function-calls delayed-execution c++11
使用C++ 11,lambdas和async执行延迟(因此也是异步)函数调用的最优雅方法是什么?建议命名:delayed_async.问的原因是我希望在给定时间(在这种情况下为一秒)之后关闭GUI警报灯而不会阻塞主(wxWidgets主循环)线程.我wxTimer为此使用了wxWidgets ,wxTimer在这种情况下我发现使用起来相当麻烦.这样得到了我的好奇如何方便多了,如果我代替实现这一点的C++ 11的async1,2.我知道在使用时我需要保护与互斥锁有关的资源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;
}
Run Code Online (Sandbox Code Playgroud)
只需确保您没有通过lambda中的引用捕获变量.
| 归档时间: |
|
| 查看次数: |
7201 次 |
| 最近记录: |