I am quite new to C/C++. I am trying to call 2 functions at time with return value. I did some research and i came to know that threading is not suitable for this as its quite difficult to get the return value through threading. I am using future library with async for this but its not calling the multiple functions at a time (i have tested it with a sleep() and i saw that it wait for other function to finish to get the return value).Please find code here ,could some please help me by showing a simple code as example?
#include <iostream>
#include <future>
#include <windows.h>
#include <string>
using namespace std;
// a non-optimized way of checking for prime numbers:
string test(string t1)
{
string h = "Hello";
string hh = h+t1;
return hh;
}
string test1(string t2)
{
string hh = "Hello";
string hhh = hh+t2;
return hhh;
}
int main ()
{
string t1 = "Hai test1";
string t2 = "Hai teset2";
future<string> stt = async (test,t1);
future<string> sttt = async (test1,t2);
string re1 = stt.get();
string re2 = sttt.get();
cout << re1 << endl;
cout << re2 << endl;
return 0;
}
You should have consulted some standard library reference: http://en.cppreference.com/w/cpp/thread/async
As you can see there std::async has an overload which takes an additional launch policy. The std::async you are calling has the following problems:
and
So in the end it depends on your compiler what happens. The solution is quite simple: