std::thread 是支持移动语义的。
1.什么时候需要移交线程归属权?
(1)我们创建一个函数,功能是创建线程,线程与后台运行,函数不用等待线程完结,将线程返回给函数的调用者。
(2)创建线程,将线程传递给某个函数,由某个函数等待线程结束,
2.如何实现线程归属权的转移
#include <iostream>
#include<stdio.h>
#include<thread>
#include<string>
#include <unistd.h>
using namespace std;
void do_something(string s)
{
for (int i = 0; i < 5; i++)
{
sleep(1);
cout<<s<<" "<<i<<endl;
}
}
std::thread f()
{
return std::thread(do_something,"f")
}
void g(std::thread t1)
{
t1.join();
}
int main()
{
std::thread t1(do_something,"t1");
t1.detach();
std::thread t2 = std::move(t1); //t1线程权转移到t2
std::thread t3 = std::thread(do_something,"t3");
t3.detach();
std::thread t4;
t4=std::move(t3); //t3线程权转移到t4
std::thread t5 = f(); //f 创见的线程权转移到t5
thread t6(do_something,"t6");
g(t6);//t6 线程权转移到函数g
sleep(6);
}
运行结果:
t1 0
t3 0
f 0
t6 0
t1 1
t3 1
f 1
t6 1
t1 2
t3 2
t6 2
f 2
t1 3
t3 3
t6 3
f 3
t1 4
t3 4
t6 4
f 4