C++Boost Asio Pool线程,带有lambda函数和传递引用变量
C++ Boost Asio Pool threading with lambda functions and pass by reference variables
我有一个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
。
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++方法中的引用变量
- 作为赋值(增加引用变量)C++的左操作数所需的左值
- 使用更改此变量的函数在同一行中打印引用变量
- 将延迟变量分配给引用变量
- 如何通过引用获取引用变量的地址?
- 将引用变量传递给函数
- C++中引用变量的内存?
- 按名称存储和引用变量列表
- 返回一个C++引用变量 VS 返回一个变量
- c++ 在 if 语句中分配引用变量
- 引用变量何时合适,为什么?你能解释一下实际的语法和位置吗?
- C++ - 将一个变量分配给另一个变量和将变量分配给引用变量有什么区别?
- 在类范围内声明时,应在 C++14 中引用变量模板
- 当引用变量的引用"死亡"时,它会发生什么?
- 将非按引用变量分配给返回按引用的函数,反之亦然
- 引用变量如何存储在mem中
- 引用变量存储在哪里