Linux 下 C++ 线程池模拟实现
什么是线程池
线程池是线程的一种管理模式,它会预先创建好线程放在容器中待命,当有任务时会分配线程完成任务,而不是当有任务时再创建新的线程。执行完任务后会重新回到线程池中进行等待。
一个简单的线程池需要包含任务队列,线程管理,任务处理,日志打印等。
线程池模拟
1. Mutex 接口封装
首先对 pthread_mutex 接口进行类封装,需要包含上锁解锁动态锁销毁锁的获取等。
紧接着将锁进行 LockGuard 再次封装,无需进行开锁解锁操作,类将帮助我们自动完成。
此处的 Get 函数是为了解决存在需要指针传递的参数问题而做的接口。
2. Cond 接口分装
线程条件变量封装接口主要有,条件变量初始化,条件等待,单线程唤醒,所有线程唤醒,动态销毁等。
3. Thread 线程封装
首先一个线程需要包含它自身的名字,线程 tid,执行函数,是否运行,是否分离等。
有了这些成员变量,我们需要实现相关函数接口,线程开始停止等待分离。
不能直接使用外部函数直接传递给 pthread_create,因为其包含了 this 指针,不符合 pthread 库本来的要求。
由于线程的接口是不包含 this 指针的,所以需要在类内部使用静态成员函数解决函数传递问题。但是静态成员函数无法调用内部成员变量。因此将 args 对象传递给 self 指针,让 self 指针完成成员间接访问。用 static 内部函数将外部的 func 函数变为了内部静态没有 this 指针的函数。
#ifndef _THREAD_H_
#define _THREAD_H_
#include <iostream>
#include <string>
#include <pthread.h>
#include <cstdio>
#include <cstring>
#include <functional>
#include "Log.hpp"
static uint32_t number = 1;
class Thread {
using func_t = std::function<void()>;
private:
{ _isdetach = ; }
{ _isrunning = ; }
{
Thread *self = <Thread *>(args);
self->();
(self->_isdetach) self->();
(self->_tid, self->_name.());
self->_func();
;
}
:
( func) : _tid(), _isdetach(), _isrunning(), (), _func(func) {
_name = + (number++);
}
{
(_isdetach) ;
(_isrunning) (_tid);
();
}
{ _name; }
{
(_isrunning) ;
n = (&_tid, , Routine, );
(n != ) {
;
} {
;
}
}
{
(_isrunning) {
n = (_tid);
(n != ) {
;
} {
_isrunning = ;
;
}
}
;
}
{
(_isdetach) {
;
}
n = (_tid, &res);
(n != ) {
(DEBUG) << ;
} {
(DEBUG) << ;
}
}
~() { }
:
_tid;
string _name;
_isdetach;
_isrunning;
*res;
_func;
};


