场景
- 创建线程并放置后台运行,但该函数本身不等待线程完结,所以需要把线程归属权交给上游函数。
- 创建线程,将其所有权传给某个函数让它负责等待该线程结束。
std::thread支持移动语义,不支持复制拷贝,对于一个具体的执行线程,其归属权可以在几个std::thread 实例间转移。
需要注意的是,如果一个std::trhead已经占有一个执行线程,那么此时再转移一个新的执行线程给它则会有错误。
void sth();
void sth_other();
下面这样是可以的:
std::thread t1(sth);
std::thread t2 = std::move(t1);
下面这样是不可以的:
std::thread t1(sth);
std::thread t2(sth_other);
t1 = std::move(t2);
下面两种方式都可以
std::thread f() {
void some_func();
return std::thread(some_func);
}
std::thread g() {
void some_func();
std::thread t(some_func);
return t;
}
No comments yet.