#pragma once
/**
* 任务池模型 TaskPool.h
*/
#include
#include
#include
#include
#include
#include
#include
class Task
{
public:
virtual void doIt()
{
std::cout << "handle a task..." << std::endl;
}
virtual ~Task()
{
std::cout << "a task destructed..." << std::endl;
}
};
class TaskPool final
{
public:
TaskPool();
~TaskPool();
TaskPool(const TaskPool &rhs) = delete;//禁止拷贝构造
TaskPool& operator=(const TaskPool &rhs) = delete;//禁止拷贝
public:
void init(int threadNum = 5);
void stop();
void addTask(Task* task);
void removeAllTasks();
private:
void threadFunc();
private:
std::list
std::mutex m_mutexList;
std::condition_variable m_cv;
bool m_bRunning;
std::vector
};
/**
* 任务池模型 TaskPool.cpp
*/
#include "TaskPool.h"
TaskPool::TaskPool() :m_bRunning(false)
{
}
TaskPool::~TaskPool()
{
removeAllTasks();
}
void TaskPool::init(int threadNum/*=5*/)
{
if (threadNum <= 0)
threadNum = 5;
m_bRunning = true;
for (int i = 0; i < threadNum; ++i)
{
std::shared_ptr
spThread.reset(new std::thread(std::bind(&TaskPool::threadFunc, this)));
m_threads.push_back(spThread);
}
}
void TaskPool::threadFunc()
{
std::shared_ptr
while (true)
{
std::unique_lock
while (m_taskList.empty())
{
if (!m_bRunning)
break;
//如果获得了互斥锁,但是条件不满足的话,m_cv.wait()调用会释放锁,且挂起当前
//线程,因此不往下执行。
//当发生变化后,条件满足,m_cv.wait() 将唤醒挂起的线程,且获得锁。
m_cv.wait(guard);
}
if (!m_bRunning)
break;
spTask = m_taskList.front();
m_taskList.pop_front();
if (spTask == NULL)
continue;
spTask->doIt();
spTask.reset();
}
std::cout << "exit thread, threadID: " << std::this_thread::get_id() << std::endl;
}
void TaskPool::stop()
{
m_bRunning = false;
m_cv.notify_all();
//等待线程退出
for (auto &iter : m_threads)
{
if (iter->joinable())
iter->join();
}
}
void TaskPool::addTask(Task *task)
{
std::shared_ptr
spTask.reset(task);
{
std::lock_guard
m_taskList.push_back(spTask);
std::cout << "add a Task" << std::endl;
}
m_cv.notify_one();
}
void TaskPool::removeAllTasks()
{
{
std::lock_guard
for (auto &iter : m_taskList)
{
iter.reset();
}
m_taskList.clear();
}
}
#include "TaskPool.h"
#include
int main()
{
TaskPool threadPool;
threadPool.init();
Task *task = NULL;
for (int i = 0; i < 100000; ++i)
{
task = new Task();
threadPool.addTask(task);
}
std::this_thread::sleep_for(std::chrono::seconds(5));
threadPool.stop();
return 0;
}