#include
<thread>
template <class F, class... Args> future<typename result_of<F(Args...)>::type> async(F&& f, Args&&... args) template <class F, class... Args> future<typename result_of<F(Args...)>::type> async(launch policy, F&& f, Args&&... args)
Startet einen (asynchronen) Ablauffaden (Thread) und liefert ein std::future<ResultType>
.
policy | Startverhalten |
f | Funktor |
args | Argumente des Aufrufs f(args…) |
Als Startverhalten können std::launch::async
oder std::launch::deferred
angegeben werden.
Rückgabewert: std::future<ResultType>
.
#include <atomic> #include <functional> #include <thread> #include <iostream> int countdown(std::atomic<int>& jobs) { int done = 0, nr; while ( (nr = int(--jobs)) >= 0) ++done; return done; } int main() { int n = 1000000; std::atomic<int> jobs(n); auto mode = std::launch::async; auto cnt1 = std::async(mode, countdown, std::ref(jobs)); auto cnt2 = std::async(mode, countdown, std::ref(jobs)); int a = cnt1.get(), b = cnt2.get(); std::cout << a << " + " << b << " = " << a+b << '\n'; assert(a+b == n); }