多线程基础知识(二):线程启动+线程传参
前言
上一节我们介绍了多线程的一些基本概念
本篇将针对如何启动线程以及线程传参进行讲解
一、线程启动的两种方式
1、detach和join
- detach:分离线程,可以与主线程一起执行,互不影响
- join:join要求先执行完线程t的workFun才能继续往下执行主线程
#include<iostream>
#include<thread>
using namespace std;
void workFun()
{
for (int n = 0; n < 40; ++n)
cout << "Hello,other thread." << endl;
}
int main()
{
thread t(workFun);
t.detach();//分离线程,可以与主线程一起执行,互不影响
//t.join();//join要求先执行完线程t的workFun才能继续往下执行主线程
for (int n = 0; n < 40; ++n)
cout << "Hello,main thread." << endl;
while (true)
{
}
return 0;
}
2、detach测试
3、join测试
二、线程传参的实现
- 实现
#include<iostream>
#include<thread>
using namespace std;
void workFun(int index)
{
for (int n = 0; n < 4; ++n)
cout << index << " Hello,other thread." << endl;
}
int main()
{
thread t(workFun, 10);
t.detach();
for (int n = 0; n < 4; ++n)
cout << "Hello,main thread." << endl;
while (true)
{
}
return 0;
}
- 图示
三、创建线程数组
- 实现 -> 注意将线程的
声明和启动分离
出来
#include<iostream>
#include<thread>
using namespace std;
void workFun(int index)
{
for (int n = 0; n < 4; ++n)
cout << index << " Hello,other thread." << endl;
}
int main()
{
thread t[3];//thread* t[3];
for (int n = 0; n < 3; ++n)
{
t[n] = thread(workFun, n);//t[n] = new thread(workFun, n);
}
for (int n = 0; n < 3; ++n)
{
t[n].detach();//t[n]->detach();
}
for (int n = 0; n < 4; ++n)
cout << "Hello,main thread." << endl;
while (true)
{
}
return 0;
}
- 图示