C++ Boost Asio 池线程与 lambda 函数和传递引用变量
C++ Boost Asio Pool threading with lambda functions and pass by reference variables
我有一个 lambda 函数,我想 post 到一个提升池。 lambda 函数使用通过引用传递的大对象。但是,我似乎无法正确编写此代码 运行。
#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;
}
是否可以post将此 lambda 函数添加到增强池中?
感谢您的宝贵时间。
您也需要捕获 f1
,就像其他变量一样。 Lambda 是一个变量:
[x, f1]{f1(x);});
(或引用)
顺便说一句,如果你想要简单的线程池执行,也可以考虑std::async
。
我有一个 lambda 函数,我想 post 到一个提升池。 lambda 函数使用通过引用传递的大对象。但是,我似乎无法正确编写此代码 运行。
#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;
}
是否可以post将此 lambda 函数添加到增强池中?
感谢您的宝贵时间。
您也需要捕获 f1
,就像其他变量一样。 Lambda 是一个变量:
[x, f1]{f1(x);});
(或引用)
顺便说一句,如果你想要简单的线程池执行,也可以考虑std::async
。