c++转移线程所有权
假设要写一个在后台启动线程的函数, 并想通过新线程返回的所有权去调用这个函数, 而不是等待线程结束再去调用;或者创建一个线程, 并在函数中转移所有权, 都必须要等待线程结束。 所以,新线程的所有权都需要转移 。这正是std::thread支持移动语义的原因。
c++标准库中含有不少资源占有类型,如std::ifstream、std::unique_ptr类、std::thread等都是可以移动但是不可复制的。因此对于一个具体的执行线程,其归属权可以在几个std::thread实例间转移。
void func1() {}
void func2() {}
int main()
{
thread t1(func1);
thread t2 = move(t1); // t1显示的将所有权交t2
// 将一个临时对象所有权交给t1,不显示调用move()的原因是,
// 所有者是一个临时对象,移动操作可以隐式进行。
t1 = thread(func2);
thread t3;
t3 = move(t2);
// 注意:这里t1已经有一个关联的线程,所以当执行到这里时,系统直接调用terminate()终止程序运行
t1 = move(t3);
}
thread支持移动操作的意义是,函数可以便捷的向外部转移线程的归属权
thread f()
{
void func1();
return thread(func1);
}
thread g()
{
void func2(int a);
thread t(func2, 10);
return t;
}
类似地,若归属权可以转移到函数内部,函数就能够接收thread实例作为按右值传递的参数
void f(thread t);
void g()
{
void func1();
f(thread(func1));
thread t(func1);
f(move(t));
}