【问题标题】:Using a temporary object to initialise thread使用临时对象初始化线程
【发布时间】:2019-03-14 07:29:57
【问题描述】:

使用在线程执行期间可能超出范围的临时线程对象初始化线程是否错误?

在下面给出的程序中,我尝试了下面给出的两种方法,它们都运行没有任何错误。

#include<thread>
using namespace std;

void consumer()
{
  for(;;)
   {}
}

int main()
{
  thread t[5];

  for(int i=0;i<5;i++)
  {
    /*
      * Method 1
      t[i]=std::thread(consumer);
    */

    /*
     * Method 2
     thread local(consumer);
     t[i]=std::move(local);
    */

     t[i].detach();
   }
   while(1)
    {}
   return 0;
}

【问题讨论】:

  • cmets 中的两种方法都可以。线程对象将存储在t 数组中,并且在main 函数本身返回之前不会超出范围。

标签: c++ multithreading initialization move object-lifetime


【解决方案1】:

这两种方法都可以正常工作。

更准确地说,operator= 在这两种情况下都会执行一次移动。所以创建线程的状态保存在t[i] 中,并且在分配之后,临时(案例1)或local(案例2)都设置为默认构造的线程,在结束语句时可能会死掉(案例1)或退出块(案例2)。

【讨论】:

    猜你喜欢
    • 2010-12-04
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多