Daily bit(e) C++ #157, Простая утилита отложенного выполнения C++11: std::async.
C++11 std::async — это простой инструмент для запуска асинхронных задач, чтобы либо запустить задачу параллельно, либо отложить выполнение в том же потоке.
Преимущество std::async заключается в простоте, поскольку std::async напрямую возвращает std::future; однако мы платим за эту простоту отсутствием контроля.
#include <future> #include <thread> #include <chrono> using namespace std::literals; // Spawn a task to run asynchronously (in a thread) auto result = std::async(std::launch::async,[](){ std::this_thread::sleep_for(200ms); }); // Wait for the task to finish result.wait(); // std::async returns a std::future auto future = std::async(std::launch::async, [](){ // Slow operation return 42; }); // Block until the result is available and then retrieve it auto value = future.get(); // value == 42 // The deferred policy will execute the packaged task on the thread // that call get()/wait(). { auto deferred = std::async(std::launch::deferred, [](){}); // Run the task on this thread. deferred.wait(); } { auto deferred = std::async(std::launch::deferred, [](){}); // Nothing prevents us from moving the future to a different thread std::jthread([handle=std::move(deferred)](){ handle.wait(); // Run the deferred task in this new thread }); }
Откройте пример в Compiler Explorer.