【问题标题】:C++ Boost Asio Pool threading with lambda functions and pass by reference variablesC++ Boost Asio 池线程与 lambda 函数并通过引用变量传递
【发布时间】:2020-11-02 20:24:45
【问题描述】:

我有一个 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 函数发布到提升池?

感谢您的宝贵时间。

【问题讨论】:

    标签: c++ multithreading boost boost-asio


    【解决方案1】:

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

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

    (或通过引用)

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

    【讨论】:

    • 谢谢。将 f1 作为这样的变量传递是不是计算成本很高?
    • 并非如此。将 lambda 视为包含捕获列表的类或结构。 (没有捕获的 lambda 是空结构,所以它像虚拟字节)
    • 代码实际上既不是作为指令集也不是作为指针传递,将代码视为 lambda 类的非虚拟方法。因此,您有效地传递了对 int large_object 的引用
    • 你是个好人,如果可以的话,我会再次向你推荐。使用这个提升池,而不是我昨天写得草率的池,让我的性能得到了很大的提升(我正在计算数字)。
    • 我通过 f1 作为参考 (&f1),但我不确定是否存在时间差异。我将不得不做更多的研究才能完全理解你在说什么。感谢您的信息和帮助。
    猜你喜欢
    • 1970-01-01
    • 2013-06-17
    • 2011-09-03
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多