C++11類庫thread 多線程編程

1.thread類構造函數

#include "stdafx.h"
#include <iostream>
#include <thread>
using namespace std;

void getThreadOne() {
	for (int i = 0; i < 5; i++) {
		cout << "執行了 1 線程" << endl;
	}
}

int main()
{
	thread trd1(getThreadOne);////創建對象trd1 參數getThreadOne爲線程入口函數 入口函數全部執行完畢 線程執行完
	trd1.join();//見後續
	return 0;
}

帶參數的構造函數

void getThreadTwo(int numA, int numB) {
	for (int i = numA; i < numB; i++) {
		cout << "執行了 2 線程" << endl;
	}
}
int main()
{
	thread trd2(getThreadTwo, 1, 5);
	trd2.join();//見後續
	return 0;
}

2.thread類join函數

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;

void getThreadOne() {
	for (int i = 0; i < 5; i++) {
		cout << "執行了 1 線程" << endl;
	}
}
int main()
{
	thread trd1(getThreadOne);
	trd1.join();//主函數運行到此處阻塞住,創建線程trd1全部執行完畢在繼續執行主函數
	cout << "主函數執行" << endl;
	return 0;
}

打印如下 線程全部執行完畢在執行的主函數
在這裏插入圖片描述

3.thread類detach函數

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;

void getThreadOne() {
	for (int i = 0; i < 5; i++) {
		cout << "執行了 1 線程" << endl;
		Sleep(1000);
	}
}
int main()
{
	thread trd1(getThreadOne);
	trd1.detach();//主函數運行到此處繼續執行
	cout << "主函數執行" << endl;
	//Sleep(5000);
	return 0;
}

打印如下 線程trd1因爲沒有阻塞,直接運行到主函數。主函數結束後 整個線程結束
在這裏插入圖片描述
detach函數主要是對線程進行分離,當對主函數進行延時Sleep(5000)後 主線程不結束 創建線程會繼續執行 如圖
在這裏插入圖片描述

4.thread類joinable函數

#include "stdafx.h"
#include <iostream>
#include <thread>
#include <Windows.h>
using namespace std;

void getThreadOne() {}
int main()
{
	thread trd;
	thread trd1(getThreadOne);
	
	cout << "默認構造函數是否可以執行join" << trd.joinable() << endl;
	cout << "構造函數是否可以執行join" << trd1.joinable() << endl;

	trd1.join();
	cout << "構造函數是否可以執行join" << trd1.joinable() << endl;
	return 0;
}

如圖 默認構造函數創建的線程不能執行join函數 能夠執行join函數的線程執行過join函數後就不能繼續join了
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章