【高質量C++/C總結11】C++線程的基本使用方式

說在開頭

我提煉了《C++ Primer》、《侯捷C++》、《高質量程序設計指南——C/C++語言》等資料中的重要部分,並總結成此博文。其中涉及到許多我個人對C++的理解,如若有不合理之處,還請朋友們多多指出,我會虛心接受每一個建議。

作者:憨豆酒(YinDou),聯繫我[email protected],熟悉圖形學,圖像處理領域,本章的源代碼可在此倉庫中找到: https://github.com/douysu/person-summary 如果大家發現錯誤以及不合理之處,還希望多多指出。

代碼部分

ThreadJoin.cpp
這一個案例解釋了線程中join方法的實例,簡單的來說就是將t1線程加在主線程之前,先讓t1線程執行。

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>   
#include <string>
/*
C++的線程案例,參考C++ Reference
1、添加join後可以保證線程的內容執行完畢,不會在主線程結束後,自定義線程中的打印內容還沒有執行完畢
*/
using namespace std;
void printThread(string s) {//線程打印方法
	std::this_thread::sleep_for(std::chrono::milliseconds(30));
	for (int i = 0; i < 50; i++) {
		cout << s;
	}
	cout << "\n";
}
int main() {
	cout << "主線程開始" << endl;
	thread t1(printThread, "*");//創建線程t1
	t1.join();
	cout << "主線程結束" << endl;
	std::cin.get();
}

這裏寫圖片描述
ThreadMutex.cpp

#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>   
#include <string>
/*
C++的線程案例,參考C++ Reference

1、打印方法結束後,如果不解鎖,那麼第二個線程的打印是無法進行的。
2、加鎖後出現的結果爲
*****************************
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&

不加鎖的結果可能爲
************&&&&&&&&&&&&********
******&&&&&&&&&
不加鎖不會保持線程的同步
*/
std::mutex myLock;//資源鎖
using namespace std;
void printThread(string s) {//線程打印方法
	myLock.lock();
	std::this_thread::sleep_for(std::chrono::milliseconds(30));
	for (int i = 0; i < 50; i++) {
		cout << s;
	}
	cout << "\n";
	myLock.unlock();
}
void printThread2(string s) {//線程打印方法
	myLock.lock();
	for (int i = 0; i < 50; i++) {
		cout << s;
	}
	cout << "\n";
	myLock.unlock();
}
int main() {
	cout << "主線程開始" << endl;
	thread t1(printThread,"*");//創建線程t1
	thread t2(printThread2, "&");//創建線程t2
	t1.join();
	t2.join();
	cout << "主線程結束" << endl;
	std::cin.get();
}

這裏寫圖片描述
如果您喜歡C++,喜歡3D,並且想了解一點深度學習的知識,加入我們的QQ羣,羣裏面全都是年輕的開發者,歡迎大家的加入討論。就說是CSDN過來的就行。
在這裏插入圖片描述

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