//ThreadPool.h
#ifndef __THREAD_POOL_
#define __THREAD_POOL_
#include<atomic>
#include<vector>
#include<thread>
#include<list>
#include<memory>
#include<mutex>
#include<string>
#include<iostream>
#include<queue>
using namespace std;
namespace Utils {
class Task
{
public:
Task(string name) {
m_name = name;
};
~Task() {};
void run() {
cout << "thread name " << m_name << endl;
};
private:
string m_name;
};
class ThreadPool {
typedef std::queue<Task*> Tasks;
using Threads = std::vector<std::thread*>;
public:
ThreadPool();
~ThreadPool();
ThreadPool(const ThreadPool&)=delete;
const ThreadPool& operator=(const ThreadPool&) = delete;
void start();
void stop();
void addTask(Task * task);
void run();
protected:
private:
std::atomic<bool> m_bStarted;//线程池开启、关闭标志位
int m_ithreadsSize{3};//线程池大小
Threads m_threads;//线程队列
std::mutex m_mutex;
Tasks m_taskList;//任务队列
std::condition_variable m_cond;
};
}
#endif
//ThreadPool.cpp
#include "stdafx.h"
#include "ThreadPool.h"
#include<assert.h>
namespace Utils {
ThreadPool::ThreadPool() {
}
ThreadPool::~ThreadPool() {
if (m_bStarted)
{
stop();
}
}
void ThreadPool::start() {
assert(m_threads.empty());
m_bStarted = true;
m_threads.reserve(m_ithreadsSize);
for (int i = 0; i < m_ithreadsSize; ++i)
{
m_threads.push_back(new std::thread(std::bind(&ThreadPool::run, this)));
}
}
void ThreadPool::stop() {
m_bStarted = true;
for (Threads::iterator it = m_threads.begin(); it != m_threads.end(); ++it)
{
(*it)->join();
delete *it;
}
m_threads.clear();
};
void ThreadPool::addTask(Task * task) {
std::unique_lock<std::mutex> lock(m_mutex);
m_taskList.push(task);
m_cond.notify_all();//通知线程开始执行
};
//线程池执行接口
void ThreadPool::run() {
while (m_bStarted)
{
std::unique_lock<std::mutex> lock(m_mutex);
//always use a while-loop, due to spurious wakeup
while (m_taskList.empty() && m_bStarted)
{
m_cond.wait(lock);
}
if (m_taskList.size()>0 && m_bStarted)
{
Task * task = m_taskList.front();
m_taskList.pop();
task->run();
}
}
};
}
//main
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include "ThreadPool.h"
using namespace std;
using namespace Utils;
int main()
{
Utils::ThreadPool threadPool;
Task * task1 = new Task("t1");
Task * task2 = new Task("t2");
Task * task3 = new Task("t3");
Task * task4 = new Task("t4");
threadPool.start();
threadPool.addTask(task1);
threadPool.addTask(task2);
threadPool.addTask(task3);
threadPool.addTask(task4);
return 0;
}
输出: