How to get return value from a function called which executes in another thread in TBB?

不问归期 提交于 2019-12-22 09:14:27

问题


In the code:

    #include <tbb/tbb.h>

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

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

Here GetSomething() was called in another thread via its pointer. But can we get return value from GetSomething()? How?


回答1:


If you are bound C++03 and tbb you have to use Outputarguments, which means that you have to rewrite your function.

e.g.:

void GetSomething(int* out_ptr);

int var = 23;

tbb::tbb:thread(GetSomething, &var); // pay attention that this doesn't run of scope

or with boost::ref you can do this:

void GetSomething(int& out);

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

If you can use C++11 the task is simplified by using futures:

e.g.:

std::future<int> fut = std::async(std::launch::async, GetSomething);

....

// later

int result = fut.get();

Here you don't have to rewrite anything.




回答2:


You can use pass by reference to get value from thread

#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


来源:https://stackoverflow.com/questions/12871836/how-to-get-return-value-from-a-function-called-which-executes-in-another-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!