代码之家  ›  专栏  ›  技术社区  ›  Dimitri C.

如何将数据传递到将在不同线程中运行的C++ 0x lambda函数?[关闭]

  •  5
  • Dimitri C.  · 技术社区  · 16 年前

    :显然,我问这个问题时得出了错误的结论。多亏了这些回答,我找到了lambda函数 [=]() 在多线程场景中工作正常。我很抱歉提出这个令人困惑的问题。请投票结束,因为这不是问题。


    DemoThread thread;
    std::string stringToPassByValue = "The string to pass by value";
    AsyncCall(thread, &DemoThread::SomeFunction, stringToPassByValue);
    

    自从引入lambda函数之后,我想将它与lambda函数结合使用。我想写以下客户端代码:

    DemoThread thread;
    std::string stringToPassByValue = "The string to pass by value";
    AsyncCall(thread, [=]()
    {
        const std::string someCopy = stringToPassByValue;
    });
    

    stringToPassByValue 不会被复制。取而代之的是 “按值捕获”功能通过引用传递数据 已经超出范围,应用程序崩溃,因为它的析构函数已经被调用。

    ?

    注意

    DemoThread thread;
    std::string stringToPassByValue = "The string to pass by value";
    AsyncCall(thread, [=](const std::string stringPassedByValue)
    {
        const std::string someCopy = stringPassedByValue;
    }
    , stringToPassByValue);
    

    更新 :全面实施 AsyncCall 太大了,不能在这里发布。简言之,发生的是 template函数实例化保存lambda函数的模板类。此类派生自包含虚拟 Execute() 函数,以及 AsyncCall() 调用,则函数调用类被放入调用队列中。然后,另一个线程通过调用 执行()

    0 回复  |  直到 16 年前