ProgramCpp
ProgramCpp

Reputation: 1390

What should be the return type of function that is run async

I was just trying out this sample to understand future and promise.

void func(std::promise<int>& p) {
  p.set_value (0);
}

int main ()
{
  std::promise<int> p;                      
  std::future<int> f = p.get_future(); 
  std::thread t(func, std::ref(p));  
  int x = fut.get();            

  t.join();
  return 0;
}

Is it ok if the return type of funcis void? If yes, can the return type be void if it is used with std::async

 std::future<int> f = std::async(std::launch::async,  func);

Is the return of async deduced to std::future< int > if the return type of func is void?

Please clarify about the return type of the function responsible for setting the promise.

also, should func be designed based on how it could be used?

Upvotes: 3

Views: 5646

Answers (1)

Galik
Galik

Reputation: 48605

In the first example the function run by the std::thread constructor can return a value or not, the value is ignored.

With a std::async call the return value of the supplied function (as determined by std::result_of) sets the template type of the returned std::future:

// function returns an int so std::async() returns a std::future<int>
std::future<int> fut = std::async(std::launch::async, []{ return 1; });

According to the C++11 standard:

30.6.8 Function template async

4 Returns: An object of type future<typename result_of<F(Args...)>::type> that refers to the shared state created by this call to async.

So in your first example it doesn't matter what the return type of the function is because its the body of the function that sets the std::promise, not the return value.

With an std::async(), however, the return statement must return the shared value to the std::future.

Upvotes: 4

Related Questions