实现线程池
线程池的核心思路与进程池类似,包含一个任务队列和若干工作线程。用户向任务队列添加任务,工作线程从队列中获取并执行。
ThreadPool 类设计
构造函数
启动线程池分为两步:创建线程对象和启动线程。在构造函数中创建 Thread 对象,传递回调函数和线程名。由于成员函数默认包含 this 指针,而封装的 Thread 类回调设计为无参无返回值,需使用 Lambda 表达式或包装器解决参数匹配问题。
ThreadPool(int threadnum = default_threadnum) : _is_running(false), _threadnum(threadnum)
{
for (int i = 0; i < _threadnum; i++)
{
std::string name = "thread-" + std::to_string(i + 1);
_threads.emplace_back([this](const std::string &name){ this->Routine(name); }, name);
}
}
Start 接口
构造函数创建线程完成后,调用 Start 接口启动线程,防止重复启动。
void Start()
{
if (_is_running) return;
_is_running = true;
for (auto &t : _threads)
{
t.Start();
}
}
线程池接入日志
在线程创建、启动、等待、回收等关键步骤输出日志,便于调试。
初步实现源码及效果图
ThreadPool.hpp
#pragma once
#include <iostream>
#include <queue>
#include
default_threadnum = ;
< T>
{
:
{
()
{
T t;
{
;
(() && _is_running)
{
_wait_thread_num++;
_cond.(_lock);
_wait_thread_num--;
}
(() && !_is_running)
{
;
}
t = _q.();
_q.();
}
();
}
}
:
( threadnum = default_threadnum) : _is_running(), _threadnum(threadnum), _wait_thread_num()
{
( i = ; i < _threadnum; i++)
{
std::string name = + std::(i + );
_threads.([]( std::string &name){ ->(name); }, name);
}
}
{
(_is_running) ;
_is_running = ;
( &t : _threads)
{
t.();
}
}
{
(!_is_running) ;
_is_running = ;
(_wait_thread_num)
{
_cond.();
}
}
{
( &t : _threads)
{
t.();
}
}
{
(!_is_running) ;
{
;
_q.(t);
(_wait_thread_num > )
{
_cond.();
}
}
}
~() {}
:
std::queue<T> _q;
std::vector<Thread> _threads;
_threadnum;
_wait_thread_num;
Mutex _lock;
Cond _cond;
_is_running;
{
_q.();
}
};


