Sunday 15 April 2012

c++ - Can a lambda that captures "this" to call a mutating member function be used to initialize a local thread? -



c++ - Can a lambda that captures "this" to call a mutating member function be used to initialize a local thread? -

i'm new concurrency, next code might troubling more experienced. question is, implementation create info races, or other problems?

the background have number crunching work do, , utilize 2 threads. while 1 thread computing intermediate results used later second, other uses generated intermediate results.

details: in phone call operator of class a, used lambda initialize first thread. lambda captures "this" pointer, in order phone call fellow member function of a, happens alter state of info members of a. captures functor, generating intermediate results.

the sec thread constructed functor, uses intermediate results producing final results.

both functors passed in via non-const references because modify own respective info members.

a 2nd question is, can move definitions of lambda functions out of loop, , utilize them build 2 threads (then join) within loop.

class a{ private: data_type m_data; void m_fun(){ // mutate m_data } public: a() = default; // functor_1 , 2 different types void operator()(functor_1&, functor_2&); }; void a::operator()(functor_1& f_1, functor_2& f_2){ t intermediate_copy_1, intermediate_copy_2; // both big, matrix structures // initial content of intermediate_copy_1 generated functor_2 // then, for(int i=0; i<100000; ++i){ auto foo = [this, &f_2, &intermediate_copy_2]{ m_fun(); f_2(intermediate_copy_2); }; auto bar = [&f_1, &intermediate_copy_1]{ f_1(intermediate_copy_1); }; std::thread t_foo(foo); std::thread t_bar(bar); t_foo.join(); t_bar.join(); // after both threads finished, pass copy_2 copy_1 utilize in next round. // copying relatively inexpensive intermediate_copy_1 = intermediate_copy_2; } // little more work }

c++ multithreading c++11 lambda

No comments:

Post a Comment