Calling mutiple functions same time with return value in c++

124 views Asked by At

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;
}
1

There are 1 answers

0
Felix Bytow On

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:

Behaves the same as async(std::launch::async | std::launch::deferred, f, args...). In other words, f may be executed in another thread or it may be run synchronously when the resulting std::future is queried for a value.

and

If both the std::launch::async and std::launch::deferred flags are set in policy, it is up to the implementation whether to perform asynchronous execution or lazy evaluation.

So in the end it depends on your compiler what happens. The solution is quite simple:

    future<string> stt = async (launch::async,test,t1);
    future<string> sttt = async (launch::async,test1,t2);

    string re1 = stt.get();
    string re2 = sttt.get();