基于C++11实现的线程池

最近在整理之前写的一些东西,方便以后查看

实现的主要原理是:一个同步队列,外部往同步队列里添加任务,然后唤醒线程有任务需要处理,线程取出任务即可。

同步队列

SyncQuene.hpp

#include <functional>
#include <mutex>
#include <list>

template<typename T>
class SyncQuene
{
	bool empty() { return m_taskList.empty(); }
	bool full() { return m_taskList.size() >= m_maxCount; }
public:
	SyncQuene(unsigned int maxCount) : m_maxCount(maxCount) {};

	void putTask(T && task)
	{
		std::unique_lock<std::mutex> lock(m_mutex);
		m_isNotFullCondition.wait(lock, [this]() ->bool {return !full(); });

		m_taskList.push_back(std::forward<T>(task));
		m_isNotEmptyCondition.notify_one();
	}

	T takeTask()
	{
		std::unique_lock<std::mutex> lock(m_mutex);
		m_isNotEmptyCondition.wait(lock, [this]() ->bool {return !empty(); });

		auto task = m_taskList.front();
		m_taskList.pop_front();
		m_isNotFullCondition.notify_one();
		return task;
	}

	bool isEmpty() 
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		return empty();
	}

	bool isFull()
	{
		std::lock_guard<std::mutex> lock(m_mutex);
		return full();
	}


private:
	unsigned int m_maxCount; 

	std::mutex m_mutex;
	std::list<T> m_taskList;
	std::condition_variable m_isNotFullCondition;
	std::condition_variable m_isNotEmptyCondition;
};

 

线程池

ThreadPool.h

#include <thread>
#include <list>
#include <memory>
#include "SyncQuene.hpp"

class ThreadPool
{
	ThreadPool(int count = std::thread::hardware_concurrency());
public:
	static ThreadPool &getInstance()
	{
		static ThreadPool s_instance;
		return s_instance;
	}
	~ThreadPool();

	void putTask(std::function<void()> &&pfunTask);

	void realase();

private:
	void runInThread();

private:
	std::list<std::shared_ptr<std::thread>> m_threadList;
	bool m_running = true;
	SyncQuene<std::function<void()>> m_taskQuenu = 1000;
};

ThreadPool.cpp

#include "stdafx.h"
#include "ThreadPool.h"


ThreadPool::ThreadPool(int count)
{
	for (int i = 0; i < count; ++i)
	{
		m_threadList.emplace_back(std::make_shared<std::thread>(std::bind(&ThreadPool::runInThread, this)));
	}
}


ThreadPool::~ThreadPool()
{
}

void ThreadPool::putTask(std::function<void()>&& pfunTask)
{
	m_taskQuenu.putTask(std::forward<std::function<void()>>(pfunTask));
}

void ThreadPool::realase()
{
	m_running = false;

	for (auto &thread : m_threadList)
	{
		if (thread)
		{
			thread->join();
		}
	}
	m_threadList.clear();
}

void ThreadPool::runInThread()
{
	while (m_running)
	{
		m_taskQuenu.takeTask()();
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值