Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 946
Nabijon Avatar asked Feb 19 '23 20:02

Nabijon


1 Answers

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.

like image 62
Stephan Dollberg Avatar answered Feb 21 '23 09:02

Stephan Dollberg