C++ 11實現的線程池

我在工作中經常使用一個線程安全的隊列在兩個線程間通信。一個線程發佈任務,一個線程處理任務,這麼做一般爲了保證發佈任務的線程及時響應網絡或其他事件。也有遇到一個線程發佈任務,多個線程處理任務的情況,一般這麼做是爲了利用多個CPU。

今天介紹一個簡單的線程池,當稍微修改代碼,把啓用線程數修改爲1的時候,就成了上面介紹的一個線程發佈任務,一個處理任務的模式。

下列代碼裏使用的threadsafe_queue的源碼在我的另一篇文章裏。thread_pool_task是用戶希望做的任何工作,我就沒有列出代碼。

#include <vector>
#include "ThreadPoolTask.h"

class thread_pool
{
public:
	thread_pool(void);
	~thread_pool(void);
public:
	void start();
	void stop();
	void add_work(thread_pool_task task);
private:
	void run();
private:
	threadsafe_queue<thread_pool_task> work_item_queue_;
	std::vector<std::thread> threads_;
	const unsigned int hardware_thread_count_;
};
#include "stdafx.h"
#include "ThreadPool.h"
#include <iostream>

using namespace std;

thread_pool::thread_pool(void):hardware_thread_count_(thread::hardware_concurrency())
{
}


thread_pool::~thread_pool(void)
{
}

void thread_pool::start()
{
	if (threads_.size() == 0)
	{
		try
		{
			for (unsigned int i = 0; i < hardware_thread_count_; i++)
			{
				threads_.push_back(thread(&thread_pool::run, this));
			}
		}
		catch (const std::system_error)
		{
			work_item_queue_.termination();
			throw;
		}

	}
}

void thread_pool::stop()
{
	work_item_queue_.termination();
	for (unsigned int i = 0 ;i<threads_.size();i++)
	{
		if(threads_[i].joinable())
		{
			threads_[i].join();
		}
	}
	threads_.clear();
}

void thread_pool::add_work(thread_pool_task task)
{
	work_item_queue_.push(task);
}

void thread_pool::run()
{
	while (true)
	{
		shared_ptr<thread_pool_task> task = work_item_queue_.wait_and_pop();
		if (task!=nullptr)
		{
			cout << this_thread::get_id() << "data:" << task->data << endl;
		}
		else
		{
			if (work_item_queue_.is_termination())
			{
				break;
			}
		}
	}
}

 

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