C++Boost Asio Pool线程,带有lambda函数和传递引用变量

C++ Boost Asio Pool threading with lambda functions and pass by reference variables

本文关键字:引用 变量 函数 lambda Pool Asio 线程 带有 C++Boost      更新时间:2023-10-16

我有一个lambda函数,我想发布到提升池中。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;
}

是否可以将此lambda函数发布到提升池?

谢谢你抽出时间。

与其他变量一样,您也需要捕获f1。Lambda是一个变量:

[x, f1]{f1(x);});

(或参考(

顺便说一句,如果您想要简单的线程池执行,也可以考虑std::async