常用线程函数
join() :
阻塞主线程,让主线程等待子线程执行完,当子线程执行完毕,这个join()就执行完毕,主线程继续执行
detach() :
从主线程中将子线程分离,主线程不必等待子线程执行完,一旦detach()之后子线程将失去与主线程的关联,
此时这个子线程就会驻留在后台运行,被c++运行时接管,当这个子线程执行完成后,由运行时库负责清理线程相关的资源。
线程创建方法
通过函数创建线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using namespace std;
void do_something(){
cout << "线程开始"<< endl;
//do something
cout << "线程结束" << endl;
}
int main(){
thread myjob (do_something);
myjob.join(); //阻塞主线程,等待子线程结束
cout << "The End" <<endl;
return 0;
}通过类创建线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using namespace std;
class myClass{
private:
int data;
public:
myClass(int d):data(d){
cout << "构造函数" <<endl;
}
myClass(const myClass&myClass1):data(myClass1.data){
cout << "拷贝构造函数" <<endl;
}
~myClass(){
cout << "析构函数" <<endl;
}
void operator()(){
//线程的入口
cout << "线程开始" <<endl;
// do something
cout << "线程结束" << endl;
}
};
int main(){
int a = 10;
myClass myclass(a);
thread myjob (myclass); // 复制一次myclass
myjob.join();
cout << "The End" <<endl;
return 0;
}通过lambda表达式创建线程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using namespace std;
int main(){
auto myLambdaThread = []{
cout << "线程开始" << endl;
// do something
cout << "线程结束" << endl;
};
thread myjob (myLambdaThread);
myjob.join();
cout << "The End" <<endl;
return 0;
}
传递临时对象作为线程参数
1 |
|
线程id
1 | 获取线程id:get_id() |
线程间的值传递
1 | std::ref() |
最多可以使用的线程数
1 | std::thread::hardware_concurrency() |