std::async 的参数的生命周期是多少?

What is the lifetime of the arguments of std::async?

似乎通过 std::async 执行的函数的参数共享未来的生命周期:

#include <iostream>
#include <future>
#include <thread>

struct S
{
    S() {
        std::cout << "S() " << (uintptr_t)this << std::endl;
    }

    S(S&& s) {
        std::cout << "S(&&) " << (uintptr_t)this << std::endl;
    }

    S(const S& s) = delete;

    ~S() {
        std::cout << "~S() " << (uintptr_t)this << std::endl;
    }
};

int main()
{
    {
        std::cout << "enter scope" << std::endl;
        auto func = [](S&& s) {
            std::cout << "func " << (uintptr_t)&s << std::endl;
            auto x = S();
        };
        S s;
        auto fut = std::async(std::launch::async, func, std::move(s));
        std::cout << "wait" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(5));
        fut.get();
        std::cout << "exit scope" << std::endl;
    }
    return 0;
}

结果:

    enter scope
  ++S() 138054661364        main's variable
  | S(&&) 138054661108 ++   std::async's internal copy
+--+S(&&) 138054659668  |   std::async's internal copy
| | S(&&) 138054922824 +--+ func's argument
+--+~S() 138054659668   | |
  | ~S() 138054661108  ++ |
  | func 138054922824     |
  | S() 138057733700   +  |  local variable
  | ~S() 138057733700  +  |
  | wait                  |
  | exit scope            |
  | ~S() 138054922824  +--+
  ++~S() 138054661364

看起来底层实现 (MSVS 2015 U3) 在地址 138054922824 处创建了参数的最终版本,但在 future 被销毁之前不会销毁它。

感觉这违反了 RAII 承诺,因为函数实现可能依赖于退出时调用的参数的析构函数。

这是错误还是传递给 std::async 的参数的确切生命周期未知?标准对此有何规定?

行为实际上是正确的:S&& 是对由 std::async 创建的中间对象的引用,其生命周期等于返回的未来的生命周期。

澄清

原来我误会了&&是什么。我错过的是 && 只是一个参考,标准并不能保证调用者会 move-construct 任何东西。调用者也可以将左值转换为右值引用。

预期流量:

  1. fut的构造函数move-construct的内部副本; fut 现在拥有 s
  2. fut 调用 func 时,它会传递另一个 move-constructed 副本作为右值; func 现在拥有 s
  3. func 退出时 s 被销毁

实际流量:

  1. fut的构造函数move-construct的内部副本; fut 现在拥有 s
  2. fut 调用 func 时,它 move-construct 是另一个内部副本,但将其作为 右值引用 传递,而不是 rvalue; fut仍然拥有s
  3. func 退出时 s 没有任何变化,因为 func 不拥有它

正如 Arne 在他的回答中所解释的那样,标准确实允许这种行为。

一个简单的解决方法是为每个生命周期必须等于 func 的生命周期的右值引用参数顶部 move-construct 本地副本(关于 func 的范围)。 =36=]

用实际答案跟进我之前的评论…

我在 libstdc++ 中遇到了相同的行为。我没有预料到这种行为,它导致了我的代码中的死锁错误(幸运的是,由于等待超时,这只会导致程序终止延迟)。在这种情况下,任务对象(我指的是函数对象f)在任务完成执行后没有被销毁,只有在未来销毁时才被销毁,但是,任务对象和实现以相同的方式处理任何参数。

std::async 的行为在 [futures.async] 中标准化。

(3.1) If launch​::​async is set in policy, calls INVOKE(DECAY_­COPY(std​::​forward<F>(f)), DECAY_­COPY(std​::​forward<Args>(args))...) ([func.require], [thread.thread.constr]) as if in a new thread of execution represented by a thread object with the calls to DECAY_­COPY() being evaluated in the thread that called async. Any return value is stored as the result in the shared state. Any exception propagated from the execution of INVOKE(DECAY_­COPY(std​::​forward<F>(f)), DECAY_­COPY(std​::​forward<Args>(args))...) is stored as the exceptional result in the shared state. The thread object is stored in the shared state and affects the behavior of any asynchronous return objects that reference that state.

通过在 INVOKE 表达式中使用未命名结果的 DECAY_COPY 的措辞,强烈建议使用在包含 [ 的完整表达式末尾销毁的临时对象=18=],这发生在新的执行线程上。但是,这还不足以得出结论,参数(的副本)不会比函数调用的寿命超过清理它们所需的处理时间(或任何 "reasonable delay")。它的推理是这样的:基本上,标准要求在执行线程完成时销毁对象。但是,标准不要求执行线程在等待调用或 future 被销毁之前完成 :

If the implementation chooses the launch​::​async policy,

(5.3) a call to a waiting function on an asynchronous return object that shares the shared state created by this async call shall block until the associated thread has completed, as if joined, or else time out ([thread.thread.member]);

因此,等待调用可能导致线程完成,然后才等待其完成。在 as-if 规则下,代码实际上可能会做更糟糕的事情,如果它们只是看起来有这种行为,例如公然将任务 and/or 参数存储在共享状态中(注意要立即遵循)。这确实是一个漏洞,IMO。

libstdc++ 的行为使得即使是无条件的 wait() 也不足以导致任务和参数被销毁——只有 get() 或未来的销毁才会。如果调用 share(),则仅销毁 shared_future 的所有副本就足以导致销毁。这似乎确实是一个错误,因为 wait() 肯定包含在 (5.3) 中的术语 "waiting function" 中,并且不会超时。除此之外,该行为似乎是 未指定的 – 无论是否是疏忽。

我猜测为什么实现似乎将对象置于共享状态,因为这比标准字面建议的实现起来容易得多(在目标线程上制作临时副本,与 std::async).

似乎应该就此提出 LWG 问题。不幸的是,对此的任何修复都可能破坏多个实现的 ABI,因此可能需要数年时间才能在部署中可靠地修复该行为,即使更改已获批准。

就我个人而言,我得出了一个不幸的结论,即 std::async 有太多的设计和实现问题,以至于它在一个重要的应用程序中几乎毫无用处。我的代码中的上述错误已通过使用我自己的(依赖项跟踪)线程池 class 替换对 std::async 的违规使用而得到解决,这会在任务完成后尽快销毁任务,包括所有捕获的对象完成执行。 (它只是从队列中弹出任务信息对象,其中包含类型擦除的任务、承诺等。)

更新:需要注意的是 libstdc++ 的 std::packaged_task 具有相同的行为,任务似乎被移动到共享状态并且不会在 std::packaged_task 时被销毁,只要get() 或任何未来的析构函数正在等待处理。