C++ 异步编程,如何不等待 future ?

标签 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.
}

Concurrency 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. */

或者,并发 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. */

另见:How to check if a std::thread is still running?

关于C++ 异步编程,如何不等待 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49338420/

相关文章:

c++ - 在std::wstring上使用std::remove_if的警告(MSVC C++ 20)

c++ - 用于按排序顺序存储元素并允许快速索引的数据结构?

javascript - Angular2 对异步/等待的 promise

javascript - 如何从异步类函数 JavaScript 返回 Promise

c++ - 将 C++ 引用从 unsigned char 转换为 double& 安全吗?

c - visual c 探查器没有给出有意义的结果

java - 来自 Thread 的警报对话框 - Android

java - 添加嵌套 View 会动态卡住应用程序

ajax - jqplot 外部数据与异步调用?

c++ - 如何检测给定的 PE 文件(exe 或 dll)是 64 位还是 32 位