.h文件
#ifndef _THREAD_POOL_H
#define _THREAD_POOL_H
#pragma once
#include "stdafx.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
namespace data_check{
class DataCheck;
struct DataParam;
}
class ThreadPool{
public:
/*
线程池任务
*/
struct Task{
Task() :user_data(nullptr), worker(nullptr),
source_prefix_path(nullptr){
}
// 任务类型
void(*job)(struct Task* task);
// 暂时不用,预留
void* user_data;
// 指向校验类
data_check::DataCheck* worker;
// hdb 名字
std::string hdb_name;
// 路径前缀
const cqWCHAR* source_prefix_path;
// 指向父节点,线程的参数
data_check::DataParam* param;
};
// 默认线程池大小为8个线程
ThreadPool(int threads_size = 8);
~ThreadPool();
// 终止线程池
void stop();
// 添加任务
void add_task(const Task& task);
// 数据库查询完毕锁以及变量
std::mutex sql_mutex;
std::condition_variable sql_cond;
private:
ThreadPool(const ThreadPool&);
const ThreadPool& operator=(const ThreadPool&);
bool is_started() const { return m_started; }
//运行线程池
void start();
// 线程函数
void thread_loop();
// 取线程池里面的任务
const Task take();
// 添加线程
void add_thread(unsigned int num);
int m_threads_size; // 线程池大小
std::vector
std::queue
std::mutex m_mutex; // STL队列不是线程安全的,因此需要结合互斥锁
std::condition_variable m_cond; // 条件变量
bool m_started; // 是否开始
std::atomic
};
.cpp文件
#include "thread_pool.h"
#define MAX_THREAD_SIZE 16
ThreadPool::ThreadPool(int threads_size)
:m_threads_size(threads_size), m_mutex(), m_cond(), m_started(false) {
start();
}
ThreadPool::~ThreadPool() {
if (m_started) {
stop();
}
}
//线程池开始
void ThreadPool::start() {
assert(m_threads.empty());
assert(!m_started);
m_started = true;
m_threads.reserve(m_threads_size);
add_thread(m_threads_size);
}
//线程池终止
void ThreadPool::stop() {
std::unique_lock
m_started = false;
lock.unlock();
while (_idle_num != m_threads.size()){
Sleep(10);
}
m_cond.notify_all();
for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
if ((*it)->joinable()) {
(*it)->join();
}
delete *it;
}
m_threads.clear();
}
void ThreadPool::add_thread(unsigned int num) {
if (num <= 0) {
return;
}
for (int i = 0; i < num && m_threads.size() < MAX_THREAD_SIZE; i++) {
m_threads.emplace_back(new std::thread(std::bind(&ThreadPool::thread_loop, this)));
++_idle_num;
}
}
//线程池循环
void ThreadPool::thread_loop() {
while (m_started) {
Task task = take();
--_idle_num;
if (nullptr != task.worker) {
task.job((Task*)&task);
++_idle_num;
}
}
}
//添加任务
void ThreadPool::add_task(const Task& task) {
std::unique_lock
m_tasks.emplace(task);
lock.unlock();
while (_idle_num < 1) {
if (m_threads.size() < MAX_THREAD_SIZE) {
add_thread(1);
break;
}
else {
Sleep(10);
}
}
m_cond.notify_one();
}
//从任务队列拿任务
const ThreadPool::Task ThreadPool::take() {
std::unique_lock
while (m_tasks.empty() && m_started) {
m_cond.wait(lock);
}
if (!m_tasks.empty() && m_started) {
// pop会destroy单个task
Task task = std::move(m_tasks.front());
m_tasks.pop();
return task;
}
return Task();
}