Reputation: 39
I wanted to know how appropriate its to use std::async
in performance oriented code. Specifically
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:
Upvotes: 3
Views: 3120
Reputation: 1
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 toasync
.
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
.
Upvotes: 2