简体   繁体   English

将参数移到std :: thread中?

[英]Moving an argument into a std::thread?

Please consider the following code: 请考虑以下代码:

void h(M m2) 
{ 
    ...
}

int main()
{
  while (true) {
    M m1 = ...;
    std::thread t(h, std::move(m1));
    t.detach();
  }
}

Is it guaranteed that m2 is properly move -d constructed from m1 before m1 is destroyed? 它是保证m2是正确move -d从构建m1之前m1被破坏? Or is there a race? 还是有种族?

The standard seems clear to me: 我觉得这个标准很明确:

Effects: Constructs an object of type thread. 效果:构造一个线程类型的对象。 The new thread of execution executes INVOKE (DECAY_COPY ( std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...) with the calls to DECAY_COPY being evaluated in the constructing thread. 新的执行线程执行INVOKE (DECAY_COPY ( std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...) ,并在构造线程中评估对DECAY_COPY的调用。

Since the copy is made in the calling thread it must complete before the constructor invocation returns. 由于复制是在调用线程中完成的,因此必须在构造函数调用返回之前完成复制。

Construction of m2 is done from a different object (the result of the DECAY_COPY), not from m1 , so it doesn't matter whether m1 has been destroyed or not. m2构造是从另一个对象(DECAY_COPY的结果)完成的,而不是从m1构造的,因此m1是否已销毁并不重要。

The result of the DECAY_COPY must be stored somewhere by the implementation so that it doesn't go out of scope until the target function has been initialized, but that is the implementation's job to get right. DECAY_COPY的结果必须由实现存储在某个位置,以便在目标函数初始化之前,它不会超出范围,但这是实现正确的工作。 Destruction of m1 doesn't have any effect on it. 销毁m1没有任何影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM