asynchronous - How tu use a C++11 lambda asynchronously when capturing by reference -
can explain behavior of next code?
when explicitely convert lambda std::function
, lambda correctly captures variable n
.
when implicitly converted std::function
(using temporary), capture fails.
i using g++-4.9 (ubuntu 4.9-20140406-1ubuntu1) 4.9.0 20140405 (experimental) [trunk revision 209157]
#include <chrono> #include <iostream> #include <memory> #include <thread> std::shared_ptr<std::thread> call(const std::function<void()>& functor) { // execute our functor asynchronously homecoming std::make_shared<std::thread>([&functor] { // create sure temporary deallocated std::this_thread::sleep_for(std::chrono::seconds(1)); // execute our functor functor(); }); } int main() { int n{}; std::cout << "in main " << &n << std::endl; // -> in main 0x7fffd4e1a96c auto lambda = [&n] { std::cout << "in lambda " << &n << std::endl; }; // here explicit convertion std::function std::cout << "explicit convertion" << std::endl; auto function = std::function<void()>{ lambda }; auto pthreadfunction = call(function); pthreadfunction->join(); // -> in lambda 0x7fffd4e1a96c // here utilize implicit convertion std::function std::cout << "implicit convertion" << std::endl; auto pthreadlambda = call(lambda); pthreadlambda->join(); // -> in lambda 0 homecoming 0; }
the lifetime of temporary constructed binding const
reference function parameter full-expression containing function call, thread function referring dangling reference.
you should capture variables thread function reference if can guarantee lifetime of variable contains lifetime of thread, have done in case function
local variable in main
.
one alternative phone call join
within full-expression constructs temporary:
call(lambda)->join();
another more general solution capture functor
value in thread function.
c++11 asynchronous lambda capture
No comments:
Post a Comment