How to get return value from a function called whi

2019-05-03 19:12发布

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?

2条回答
一纸荒年 Trace。
2楼-- · 2019-05-03 19:46

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.

查看更多
虎瘦雄心在
3楼-- · 2019-05-03 19:58

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
查看更多
登录 后发表回答