使用临时对象初始化线程
Using a temporary object to initialise thread
使用线程执行期间可能超出范围的临时线程对象初始化线程是否错误?
在下面给出的程序中,我已经尝试了下面给出的 2 种方法并且它们 运行 都没有任何错误。
#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=
在这两种情况下都执行了一步。所以创建的线程的状态保存在 t[i]
并且在赋值之后,临时(情况 1)或 local
(情况 2)都设置为默认构造的线程,可以在结束时死亡语句(情况 1)或退出块(情况 2)。
使用线程执行期间可能超出范围的临时线程对象初始化线程是否错误?
在下面给出的程序中,我已经尝试了下面给出的 2 种方法并且它们 运行 都没有任何错误。
#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=
在这两种情况下都执行了一步。所以创建的线程的状态保存在 t[i]
并且在赋值之后,临时(情况 1)或 local
(情况 2)都设置为默认构造的线程,可以在结束时死亡语句(情况 1)或退出块(情况 2)。