【问题标题】:How to get return value from a function called which executes in another thread in TBB?如何从在 TBB 的另一个线程中执行的被调用函数获取返回值?
【发布时间】:2012-10-13 09:33:41
【问题描述】:

在代码中:

    #include <tbb/tbb.h>

    int GetSomething()
    {
        int something;
        // do something
        return something;
    }

    // ...
    tbb::tbb_thread(GetSomething, NULL);
    // ...

这里GetSomething() 通过它的指针在另一个线程中被调用。但是我们可以从GetSomething() 获得返回值吗?怎么样?

【问题讨论】:

    标签: c++ multithreading return-value function-pointers tbb


    【解决方案1】:

    如果你绑定了 C++03 和 tbb,你必须使用 Outputarguments,这意味着你必须重写你的函数。

    例如:

    void GetSomething(int* out_ptr);
    
    int var = 23;
    
    tbb::tbb:thread(GetSomething, &var); // pay attention that this doesn't run of scope
    

    或使用boost::ref,您可以这样做:

    void GetSomething(int& out);
    
    int var = 23;
    tbb::tbb_thread(GetSomething, boost::ref(var)); // pay attention here, too
    

    如果您可以使用 C++11,则使用 futures 可以简化任务:

    例如:

    std::future<int> fut = std::async(std::launch::async, GetSomething);
    
    ....
    
    // later
    
    int result = fut.get();
    

    在这里你不必重写任何东西。

    【讨论】:

      【解决方案2】:

      您可以使用传递引用从线程中获取值

      #include <tbb/tbb.h>
      
      void GetSomething(int *result)
      {
      
          result= // do something
      }
      
      // ...
      int result;
      tbb::tbb_thread(GetSomething, &result);
      tbb.join();
      //use result as you like
      

      【讨论】:

      • 您所做的更改使您的代码无效,std::ref 创建了一个不等于 &amp;varstd::reference_wrapper,它返回变量的地址。除此之外,std::ref 是 C++11,它将调用计划中的期货。
      猜你喜欢
      • 2013-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 2021-02-07
      • 1970-01-01
      相关资源
      最近更新 更多