-
示例程序
#include<iostream>
#include<thread>
// sleep 函数的类,Windows下是 Windows.h 头文件
#include<unistd.h>
using namespace std;
void thread_1(){
for(int i=0; i<5; i++){
cout<<"thread 1 is working"<<endl;
sleep(1);
}
}
void thread_2(){
for(int i=0; i<5; i++){
cout<<"thread 2 is working"<<endl;
sleep(1);
}
}
int main(){
thread task_1(thread_1);
thread task_2(thread_2);
cout<<"执行join函数"<<endl;
task_1.join();
task_2.join();
cout<<"join函数执行完成"<<endl;
for(int i=0; i<5; i++){
cout<<"main thread is working"<<endl;
sleep(1);
}
return 0;
}
程序执行结果:
thread.join()函数会阻塞主线程,当执行到join函数时,会阻塞主线程的执行,所以主线程的输出在最后才出现。
当我们把join函数放到最后会发现主线程有输出
#include<iostream>
#include<thread>
// sleep 函数的类
#include<unistd.h>
using namespace std;
void thread_1(){
for(int i=0; i<5; i++){
cout<<"thread 1 is working"<<endl;
sleep(.5);
}
}
void thread_2(){
for(int i=0; i<5; i++){
cout<<"thread 2 is working"<<endl;
sleep(.5);
}
}
int main(){
thread task_1(thread_1);
thread task_2(thread_2);
for(int i=0; i<5; i++){
cout<<"main thread is working"<<endl;
sleep(.5);
}
cout<<"执行join函数"<<endl;
task_1.join();
task_2.join();
cout<<"join函数执行完成"<<endl;
return 0;
}
输出:
可以发现主线程正常输出,这是因为我们将join函数放到了最后,所以主线程并不会阻塞。
-
thread.detach()函数不会阻塞主线程
#include<iostream>
#include<thread>
// sleep 函数的类
#include<unistd.h>
using namespace std;
void thread_1(){
for(int i=0; i<5; i++){
cout<<"thread 1 is working"<<endl;
sleep(.5);
}
}
void thread_2(){
for(int i=0; i<5; i++){
cout<<"thread 2 is working"<<endl;
sleep(.5);
}
}
int main(){
thread task_1(thread_1);
thread task_2(thread_2);
cout<<"执行detach函数"<<endl;
task_1.detach();
task_2.detach();
cout<<"detach函数执行完成"<<endl;
for(int i=0; i<5; i++){
cout<<"main thread is working"<<endl;
sleep(.5);
}
return 0;
}
输出:
使用detach函数,三个线程并行执行,并没有阻塞主线程。
-
thread传参
#include<iostream>
#include<thread>
// sleep 函数的类
#include<unistd.h>
using namespace std;
void thread_1(char num){
for(int i=0; i<num-'0'; i++){
cout<<"thread 1 is working"<<endl;
sleep(.5);
}
}
void thread_2(int num){
for(int i=0; i<5; i++){
cout<<"thread 2 is working"<<endl;
sleep(.5);
}
}
int main(){
// 传入参数
thread task_1(thread_1,'5');
thread task_2(thread_2,5);
cout<<"执行detach函数"<<endl;
task_1.detach();
task_2.detach();
cout<<"detach函数执行完成"<<endl;
for(int i=0; i<5; i++){
cout<<"main thread is working"<<endl;
sleep(.5);
}
return 0;
}
输出:
-
线程同步 mutex
使用mutex对多个线程访问的数据进行上锁,防止数据出现异常
#include<iostream>
#include<thread>
// sleep 函数的类
#include<unistd.h>
// 线程锁
#include<mutex>
using namespace std;
// 全局变量
int var = 0;
// 锁
mutex mt;
void add_num(){
// 上锁,如果有多个线程同时访问,那么就必须排队
mt.lock();
var++;
sleep(.3);
// 解锁,解除当前线程对数据的占用
mt.unlock();
}
void thread_1(){
for(int i=0; i<5; i++){
add_num();
cout<<"thread 1 : "<< var <<endl;
}
}
void thread_2(){
for(int i=0; i<5; i++){
add_num();
cout<<"thread 2 : "<< var <<endl;
}
}
int main(){
thread task_1(thread_1);
thread task_2(thread_2);
task_1.detach();
task_2.detach();
sleep(2);
return 0;
}
输出: