-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadpool.h
More file actions
62 lines (49 loc) · 1.77 KB
/
threadpool.h
File metadata and controls
62 lines (49 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#pragma once
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define COUNT 2 // 一次增加或减少的线程个数
// 任务结构体
typedef struct Task {
void (*process)(void *arg); // 处理函数
void *arg; // 处理函数的参数
} Task;
// 线程池结构体
typedef struct ThreadPool {
// 任务队列
Task *qTasks; // 底层数组
int qCapacity; // 数组容量
// 方便队列出入元素
int qFront; // 队首
int qRear; // 队尾
int qTaskCount; // 当前任务数
pthread_t *workerThreadIDs; // 工作线程数组
pthread_t managerThreadID; // 管理者线程
int minThreads; // 最小线程数
int maxThreads; // 最大线程数
int busyCount; // 忙碌线程计数
int liveCount; // 存活线程计数
int exitCount; // 退出线程计数
int shutdown; // 关闭标志
pthread_mutex_t poolMutex; // 保护线程池的互斥锁
pthread_mutex_t busyMutex; // 保护busyCount的互斥锁
pthread_cond_t notEmpty; // 队列非空条件
pthread_cond_t notFull; // 队列未满条件
} ThreadPool;
// 创建线程池
ThreadPool *threadpoolCreate(int min, int max, int queueCapacity);
// 销毁线程池
int threadpoolDestroy(ThreadPool *pool);
// 添加任务到线程池
void threadpoolAddTask(ThreadPool *pool, void (*process)(void *), void *arg);
// 管理者线程函数
void *manager(void *arg);
// 工作线程函数
void *worker(void *arg);
// 单个线程退出
void threadExit(ThreadPool *pool);
// 获取线程池状态
int threadpoolGetBusyCount(ThreadPool *pool);
int threadpoolGetAliveCount(ThreadPool *pool);