[英]C++ Boost Asio Pool threading with lambda functions and pass by reference variables
I have a lambda function I would like to post to a boost pool.我有一个 lambda function 我想发布到提升池。 The lambda function makes use of a large object which is passed by reference. lambda function 使用通过引用传递的大 object。 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?是否可以将此 lambda function 发布到提升池?
Thank you for your time.感谢您的时间。
You need to capture f1
too, just like other variables.您也需要捕获f1
,就像其他变量一样。 Lambda is a variable: Lambda 是一个变量:
[x, f1]{f1(x);});
(Or by reference) (或参考)
By the way, if you want simple thread pool execution, consider also std::async
.顺便说一句,如果你想要简单的线程池执行,也可以考虑std::async
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.