Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is std::async implemented?

I wanted to know how appropriate its to use std::async in performance oriented code. Specifically

  1. Is there any penalty in catching the exception from worker thread to main thread?
  2. How are the values returned from worker to main?
  3. Are the input arguments passed by ref actually never get copied or not?

I am planning to pass a heavy session object to a thread or write std::async.

bool fun(MySession& sessRef);
MySession sess;
auto r = std::async(&fun, sess);

EDIT:

  • I am planning to use it with GCC 4.9.1 and VS2013 both since the application is platform agnostic. However most deployments will be *nix based so atleast GCC should be performant.
like image 405
prem.baranwal Avatar asked Apr 15 '26 13:04

prem.baranwal


1 Answers

We can't tell exactly "how is std::async implemented", since you're not referring to a particular toolchain that provides that implementation actually.

1. Is there any penalty in catching the exception from worker thread to main thread?


Define "Penalty" by which means exactly? That can't be answered unless you clarify about your concerns/requirements.
Usually there shouldn't be any penalty, by just catching the exception in the thread, that created the throwing one. It's just about the exception may be provided to the creating thread via the join(), and this causes some cost for keeping that particular exception through handling of join().

2. How are the values returned from worker to main?


To cite what's the c++ standards definition saying about this point:

30.6.8 Function template async

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


3. Are the input arguments passed by ref actually never get copied or not?

That point is answered in detail here: Passing arguments to std::async by reference fails. As you see, the default case they are copied.
According to @Yakk's comment, it might be possible to pass these parameters via std::ref to avoid operating on copies, but take references.


how is std::async implemented

I can tell only for the c++ standards requirements, how it should be implemented, unless you're referring to a particular toolchain, that tries to provide a proper implementation of std::async.

like image 109
πάντα ῥεῖ Avatar answered Apr 17 '26 03:04

πάντα ῥεῖ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!