介绍
C Linux实现线程池技术
作者第一次编写的线程池,推荐使用的时候修改thread_manager函数中部分逻辑
支持库
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
代码
ThreadPool.h
typedef struct MissionAttr
{
void (*mission)(void *);
void *param;
time_t createTime;
char state;
} MissionAttr;
typedef struct MissionNode
{
MissionAttr *mission;
struct MissionNode *next;
struct MissionNode *back;
} MissionNode;
typedef struct MissionList
{
MissionNode *front;
MissionNode *final;
} MissionList;
typedef struct ThreadAttr
{
pthread_t id;
time_t createTime;
char state;
} ThreadAttr;
typedef struct ThreadNode
{
ThreadAttr *threadAttr;
struct ThreadNode *next;
struct ThreadNode *back;
} ThreadNode;
typedef struct ThreadList
{
ThreadNode *front;
ThreadNode *final;
} ThreadList;
typedef struct ThreadPool
{
int controlThreadId;
ThreadList *threadList;
MissionList *missionWaiting;
MissionList *missionList;
pthread_t managerID;
int waitingMissionNumber;
int hanldingMissionNumber;
int busyNumber;
int freeNumber;
int needCloseNumber;
int maxNumber;
int minNumber;
int existNumber;
char close;
pthread_mutex_t managerMutex;
pthread_mutex_t missionMutex;
pthread_mutex_t threadMutex;
pthread_mutex_t workerMutex;
pthread_cond_t workerCond;
} ThreadPool;
typedef struct ThreadArgs
{
ThreadPool *threadPool;
ThreadNode *threadNode;
} ThreadArgs;
// 主要函数
// 创建线程池
ThreadPool *create_thread_pool(int minNumber, int maxNumber);
// 提交任务
void thread_pool_submit(ThreadPool *threadPool, void *func, void *args);
// 启动线程池
int thread_pool_run(ThreadPool *threadPool);
// 关闭并释放线程池
void thread_shutdown_and_free(ThreadPool *threadPool);
// 其他函数
// 管理者线程
void *thread_manager(void *args);
// 工作者线程
void *thread_worker(void *args);
// 创建工作者线程
int creater_thread_worker(ThreadPool *threadPool, int number);
// 获取等待中的任务
MissionNode *get_mission(ThreadPool *threadPool);
// 释放完成的任务
void free_mission(ThreadPool *threadPool, MissionNode *missionNode);
// 基础函数
// 申请内存修复版
void *fixMalloc(size_t size);
ThreadPool.c
#include "./ThreadPool.h"
void *fixMalloc(size_t size)
{
void *tmp = NULL;
while (1)
{
tmp = malloc(size);
if (tmp)
{
break;
}
sleep(1);
}
return tmp;
}
ThreadPool *create_thread_pool(int minNumber, int maxNumber)
{
ThreadPool *threadPool = (ThreadPool *)fixMalloc(sizeof(ThreadPool));
memset(threadPool, 0, sizeof(ThreadPool));
threadPool->minNumber = minNumber;
threadPool->maxNumber = maxNumber;
pthread_mutex_init(&threadPool->missionMutex, NULL);
pthread_mutex_init(&threadPool->threadMutex, NULL);
pthread_mutex_init(&threadPool->workerMutex, NULL);
pthread_cond_init(&threadPool->workerCond, NULL);
pthread_mutex_init(&threadPool->managerMutex, NULL);
threadPool->threadList = (ThreadList *)fixMalloc(sizeof(ThreadList));
threadPool->missionList = (MissionList *)fixMalloc(sizeof(MissionList));
threadPool->missionWaiting = (MissionList *)fixMalloc(sizeof(MissionList));
memset(threadPool->threadList, 0, sizeof(ThreadList));
mems