How to get the return value from a function that executes on another thread in TBB?

In code:

#include <tbb/tbb.h> int GetSomething() { int something; // do something return something; } // ... tbb::tbb_thread(GetSomething, NULL); // ... 

Here GetSomething() is called on another thread through its pointer. But can we get the return value from GetSomething() ? How?

+4
source share
2 answers

If you are connected with C ++ 03 and tbb, you should use Outputarguments, which means you need to rewrite your function.

eg:.

 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, simplify the task with futures :

eg:.

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

You don’t need to rewrite anything here.

+4
source

You can use pass by reference to get the value from the stream

 #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 
+4
source

Source: https://habr.com/ru/post/1439529/


All Articles