最近在整理之前写的一些东西,方便以后查看
实现的主要原理是:一个同步队列,外部往同步队列里添加任务,然后唤醒线程有任务需要处理,线程取出任务即可。
同步队列
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()();
}
}