Kerrek SB is correct in its answer, but I suggested adding another example (which, in his opinion, should be the answer, so here it is).
I recently discovered that, at least in VC11, std::async will not release all thread resources until the end of the application , which allows a memory leak to be false-positive (if you control them, for example, Visual Leak Detector).
Here I mean that in most basic applications you should not look at the rest of this answer, but if I like you need to check for a memory leak and cannot afford false positives like static data not released at the end of the main function. If this is your case, then this may help.
std::async will not start in a separate thread by default only if you use std::launch::async as the first parameter. Otherwise, the implementation will decide what to do and that the new Microsoft Concurrency Runtime task manager will be used to implement VC11 to manage the provided function as a task defined in the task pool, which means that threads are supported and managed in a transparent manner. There are ways to explicitly stop working with the task manager, but this is too platform-specific, making it asynchronous if you want exactly 1) do not forget to start the thread and 2) get the result later, and 3) make sure the thread is completely freed when you get the result .
An alternative that does just that is to use std::packaged_task and std::thread in combination with std::future . The way this is done is almost like using std::async , a bit more verbose (which means you can generalize it to a custom template function if you want).
#include <packaged_task> #include <thread> int myfun(double, char, bool); std::packaged_task<int(double, char, bool)> task(myfun, arg1, arg2, arg3); auto f = task.get_future(); // f is a std::future<int>
First, we create a task, basically an object containing both a function and std::promise , which will be associated with the future. std::packaged_task works basically like an extended version of std::function :
Now we need to explicitly execute the stream:
std::thread thread(std::move(task)); thread.detach();
Moving is necessary because std::packaged_task not copied. Disconnecting a stream is only necessary if you want to synchronize only with the help of the future - otherwise you will need to explicitly join the stream. If you do not, when the thread destructor is called, it will just call std::terminate() .
// ... int res = f.get(); // Synchronization and retrieval.