I have a lambda function I would like to post to a boost pool. The lambda function makes use of a large object which is passed by reference. However, I can't seem to make this code run properly.
#include <boost/asio.hpp>
#include <iostream>
int main() {
int large_object = 10;
auto f1 = [&large_object](int x) {
std::cout << "this is a very large object that needs passed by ref " << large_object << std::endl;
std::cout << x << std::endl;
std::this_thread::sleep_for(std::chrono::seconds {3});
std::cout << "DONE SLEEPING!" << std::endl;
};
int processor_count = 2; // consider that this CPU has two processors
// Launch the pool with n threads.
boost::asio::thread_pool pool(processor_count);
int x = 2;
// Submit a function to the pool.
boost::asio::post(pool, [x]{f1(x);});
pool.join();
return 0;
}
Is it possible to post this lambda function to a boost pool?
Thank you for your time.
You need to capture f1
too, just like other variables. Lambda is a variable:
[x, f1]{f1(x);});
(Or by reference)
By the way, if you want simple thread pool execution, consider also std::async
.