C++ std::thread的基礎使用和管理


1. 基本的介紹和使用

參考菜鳥教程的相關介紹,涉及各種構造函數和其他成員函數的使用。

https://www.runoob.com/w3cnote/cpp-std-thread.html

下面這篇文章也有比較豐富的使用例子:

https://blog.csdn.net/ouyangfushu/article/details/80199140

下面這篇闡述了創建線程的三種方式(1)函數(2)類對象(3)Lambda表達式

https://blog.csdn.net/fly_wt/article/details/88986993

2. 用shared_ptr進行多個線程的管理

主要面臨的問題是這樣的:

(1)在一個程序之中,主線程會創建多個線程執行不同的任務,主線程不需要被阻塞;

(2)主線程最后會執行一系列清理任務,這些清理任務執行之前需要等待所有的子線程執行完畢。

 

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

class ThreadTest
{
public:
	void normalthread()
	{
		cout<<"Normal thread" << to_string(count++) << endl;
	}

	void endthread()
	{
		for (auto iter = m_threadlist.begin(); iter != m_threadlist.end();iter++)
		{
			(*iter)->join();
		}
		cout << "End Thread" << endl;
	}

	void run()
	{
		for (int i = 0; i < 10; i++)
		{
			Sleep(10);
			m_threadlist.push_back(make_shared<thread>(&ThreadTest::normalthread,this));
		}

		m_endThread = make_shared<thread>(&ThreadTest::endthread, this);
		m_endThread->join();
	}

private:
	uint32_t count;
	vector<shared_ptr<thread>> m_threadlist;
	shared_ptr<thread> m_endThread;
};

 

  程序當中需要注意的點有以下幾個:

(1)thread的管理使用一個vector<shared_ptr<thread>>而不是thread本身的vector,避免thread本身的拷貝構造;

(2)再向thread的vector插入元素的時候,make_shared<thread>的參數需要傳遞函數指針和類的this指針。

  相關討論:https://segmentfault.com/q/1010000015755911?utm_source=tag-newest

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM