aja*_*aja 1 c++ multithreading asynchronous c++17
我正在尝试用 C++ 学习异步编程。在 Python 中,我们有await,我们可以从那个点恢复函数,但在 C++ 中future等待结果并停止下一行代码。如果我们不想得到结果,而是继续下一行代码怎么办?我怎样才能做到这一点?
您可以使用std::future::wait_for来检查任务是否已完成执行,例如:
if (future.wait_for(100ms) == std::future_status::ready) {
// Result is ready.
} else {
// Do something else.
}
Run Code Online (Sandbox Code Playgroud)
的并发TS包括std::future::is_ready(可以包括在C ++ 20),这是无阻塞。如果它被包含在标准中,用法将类似于:
auto f = std::async(std::launch::async, my_func);
while (!f.is_ready()) {
/* Do other stuff. */
}
auto result = f.get();
/* Do stuff with result. */
Run Code Online (Sandbox Code Playgroud)
可替代地,并发TS还包括std::future::then,其解读,可以使用例如为:
auto f = std::async(std::launch::async, my_func)
.then([] (auto fut) {
auto result = fut.get();
/* Do stuff when result is ready. */
});
/* Do other stuff before result is ready. */
Run Code Online (Sandbox Code Playgroud)