使用临时线程对象初始化线程是否错误,该对象在线程执行期间可能会超出范围?
在下面给出的程序中,我尝试了下面给出的两种方法,并且它们都运行没有任何错误。
#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;
}
最佳答案
两种方法都可以正常工作。
更准确地说,operator=
在两种情况下都执行 move 。因此,创建的线程的状态保存在 t[i]
中,并且在赋值之后,临时(情况 1)或 本地
(情况 2)都设置为默认构造的线程,在结束语句(情况 1)或退出 block (情况 2)时可能会终止。
关于c++ - 使用临时对象来初始化线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55157064/