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;
			}
		}
	}
}

 

猜你喜欢

转载自blog.csdn.net/weixin_41855721/article/details/82292018