c++ - std::promise 能否知道相应的 std::future 已取消等待?

标签 c++ multithreading c++11 std-future

我所处的情况是,我有一个连续的线程处理某些输入。然而,有时工作量太大,相应的 future 不会等待结果。 在这种情况下,我需要释放一些资源,因为计算结果将不会被继续(在其他地方标记为能够释放)。

Promise 是否有可能知道各自的 future 已经停止等待? 或者我可以通过其他方式达到这个效果吗? (shared_future,...?)

作为概念的概述,我修改了 std::promise example ,为了让您更容易理解我的意思:

using namespace std::chrono_literals;

void accumulate(std::vector<int>::iterator first,
                std::vector<int>::iterator last,
                std::promise<int> accumulate_promise)
{
    int sum = std::accumulate(first, last, 0);

    /* Can I possibly know that the corresponding future has stopped 
     * waiting for this promise, at this very position? 
     */
    accumulate_promise.set_value(sum);
}

int main()
{
    std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
    std::promise<int> accumulate_promise;
    std::future<int> accumulate_future = accumulate_promise.get_future();
    std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
                            std::move(accumulate_promise));

    /* Do not wait forever */
    accumulate_future.wait_for(1ms);
}

最佳答案

不是通过std::promise。您可以在 promise 旁边包含一个 token ,以指示它是否应该继续。

using namespace std::chrono_literals;

void accumulate(std::vector<int>::iterator first,
                std::vector<int>::iterator last,
                std::promise<int> accumulate_promise,
                std::atomic<bool> & cancellation_token)
{
    int sum = std::accumulate(first, last, 0);

    if (cancellation_token.load()) return;

    accumulate_promise.set_value(sum);
}

int main()
{
    std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
    std::promise<int> accumulate_promise;
    std::atomic<bool> token(false);
    std::future<int> accumulate_future = accumulate_promise.get_future();
    std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
                            std::move(accumulate_promise), std::ref(token));

    if (accumulate_future.wait_for(1ms) != std::future_status::ready)
    {
        token.store(true);
    }
}

关于c++ - std::promise 能否知道相应的 std::future 已取消等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48526898/

相关文章:

c++ - Qt 与正在运行的工作线程的通信

c++ - 给自己一个 std::shared_ptr<std::thread> 。定义或未定义的行为

c++ - 具有初始化列表的类启动 std::array 成员变量

c++ - 将十六进制值保存到 C++ 字符串

c - 为什么我的消费者线程在我的生产者线程完成之前就停止了?

java - 如果我保留对 Runnable 的引用,它运行的线程何时会被释放?

c++ - 为什么在std::condition_variable notify_all的运行速度比notify_one更快(在随机请求上)?

c++ - C++ 中的构造函数初始化列表

c++ - 如何在 C++ 函数中正确使用指针?

c++ - 绘制大量重叠的二维阴影