1. 程式人生 > >通俗易懂地理解執行緒池&&C++程式碼例項與講解

通俗易懂地理解執行緒池&&C++程式碼例項與講解

本機環境:win10   64   vs2017


C++新手,程式碼寫得比較一般,高手見諒(抱拳)。

歡迎留言交流


簡介執行緒池:

在介紹執行緒池之前,我們要首先知道多執行緒是啥。

單執行緒:就是說你現在有四件毫不相干的事情要分別去做,那你只有把一件事情做完在接著做下一件事情了,(你)->A->B->C->D。

多執行緒:好了,現在你可以分身了。(你)->(你'+你''+你'''+你'''')

那麼,現在你可以這樣做事:(你')->A,(你'')->B,(你''')->C,(你'''')->D

這就是多執行緒。不同事情或者同一事情,你可以交給每個分身去做。

這時大家大概知道多執行緒是怎麼一回事了吧:就是同一時間執行多個任務。

 

那麼執行緒池是用來幹啥的?我們可以看到多執行緒提高了CPU的使用率和程式的工作效率,但是如果有大量的執行緒,就會影響效能(建立與銷燬),因為CPU需要在它們之間切換,而且更多的執行緒需要更多的記憶體空間,同時多執行緒操作可能會出現執行緒安全或者死鎖等問題。

咋辦?

——執行緒池。

執行緒池可以想象成一個裝東西的盒子,它的作用就是讓每一個執行緒結束後,並不會銷燬,而是放回到執行緒池中成為空閒狀態,等待下一個物件來使用。

因此,執行緒池可以減少建立與銷燬執行緒帶來的效能開銷。可控制最大併發執行緒數,避免過多資源競爭而導致系統記憶體消耗完。能更好的控制執行緒的開啟與回收,並且能定時執行任務。

好了,知道了原理我們就可以來實際應用了:

首先建立txt文件,將以下程式碼複製進去

#ifndef THREAD_POOL_H
#define THREAD_POOL_H

#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>

class ThreadPool {
public:
	ThreadPool(size_t);
	template<class F, class... Args>
	auto enqueue(F&& f, Args&&... args)
		->std::future<typename std::result_of<F(Args...)>::type>;
	~ThreadPool();
private:
	// need to keep track of threads so we can join them
	std::vector< std::thread > workers;
	// the task queue
	std::queue< std::function<void()> > tasks;

	// synchronization
	std::mutex queue_mutex;
	std::condition_variable condition;
	bool stop;
};

// the constructor just launches some amount of workers
inline ThreadPool::ThreadPool(size_t threads)
	: stop(false)
{
	for (size_t i = 0; i < threads; ++i)
		workers.emplace_back(
			[this]
	{
		for (;;)
		{
			std::function<void()> task;

			{
				std::unique_lock<std::mutex> lock(this->queue_mutex);
				this->condition.wait(lock,
					[this] { return this->stop || !this->tasks.empty(); });
				if (this->stop && this->tasks.empty())
					return;
				task = std::move(this->tasks.front());
				this->tasks.pop();
			}

			task();
		}
	}
	);
}

// add new work item to the pool
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
	using return_type = typename std::result_of<F(Args...)>::type;

	auto task = std::make_shared< std::packaged_task<return_type()> >(
		std::bind(std::forward<F>(f), std::forward<Args>(args)...)
		);

	std::future<return_type> res = task->get_future();
	{
		std::unique_lock<std::mutex> lock(queue_mutex);

		// don't allow enqueueing after stopping the pool
		if (stop)
			throw std::runtime_error("enqueue on stopped ThreadPool");

		tasks.emplace([task]() { (*task)(); });
	}
	condition.notify_one();
	return res;
}

// the destructor joins all threads
inline ThreadPool::~ThreadPool()
{
	{
		std::unique_lock<std::mutex> lock(queue_mutex);
		stop = true;
	}
	condition.notify_all();
	for (std::thread &worker : workers)
		worker.join();
}

#endif

並改名為  ThreadPool.h  如下:

接著開啟vs2017的安裝目錄,右上角搜尋MSCV,開啟這個資料夾:

 

然後依次開啟資料夾“14.15.26726”->“include”

在“include”目錄下把剛才的ThreadPool.h移入。

 

二、下面開始簡單的程式碼實現(C++):

#include "pch.h"
#include <iostream>
#include "ThreadPool.h"

using namespace std;

int main()
{
	while (true)
	{
		//初始化執行緒池,3個執行緒
		ThreadPool pool(3);
		//vector是一個序列容器,std::future 可以用來獲取非同步任務的結果(可以理解為用來判斷某條執行緒可以執行新任務與否)
		std::vector< std::future<int> > results;
		for (int j = 0; j < 3; ++j)
		{
			//在vector的末尾插入一個新元素
			results.emplace_back
			(
				//執行緒池佇列
				pool.enqueue
				([j]
			{
				//不斷輸出現在是哪條執行緒(j)在工作
				while (true)
				{
					cout << j<<"\t";
				}
				return 0;
			}
				)
			);
		}
	}
	return 0;
}

結果(部分截圖):

通過這個輸出我們就可以看到各執行緒的呼叫與執行情況。