【发布时间】: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