实现线程池
✏ 线程池
🖋 1、作用:异步解耦
线程池的运行逻辑:线程池中的线程在不断竞争任务队列中的任务。
🖋 2、组成
- 任务队列
- 线程集合
- 管理组件
🖋 3、TODO
- 增加线程
- 删除过度冗余的线程
- 快手面试题:查询一个任务是否被执行完,生产者消费者模式(任务队列用环形阻塞队列即可)
- 头条面试题:如果一个任务在执行过程中线程被中断(也许是时钟周期已到,也许是等待资源,也许是被中断,等等),后面怎样保证继续被同一个线程执行。
C-glibc实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define LL_ADD(item, list) do { \
item->prev = NULL; \
item->next = list; \
if (list != NULL) \
list->prev = item; \
list = item; \
}while(0) // 和使用时的分号做统一
#define LL_REMOVE(item, list) do { \
if(item->prev != NULL) \
item->prev->next = item->next; \
if(item->next != NULL) \
item->next->prev = item->prev; \
if(item == list) \
list = item->next; \
item->prev = item->next = NULL; \
}while(0)
// 任务结构体
struct NJOB {
void (*func)(int arg, pthread_t id);
int user_data;
pthread_t id;
struct NJOB *next;
struct NJOB *prev;
};
struct NWORKER {
pthread_t id;
int terminate; // 是否工作
struct NMANAGER *pool;
struct NWORKER *prev;
struct NWORKER *next;
};
typedef struct NMANAGER {
pthread_mutex_t mtx;
pthread_cond_t cond;
struct NJOB *jobs;
struct NWORKER *workers;
}nThreadPool;
// 线程的回调函数
void *thread_cb(void *arg){
struct NWORKER *worker = (struct NWORKER *)arg;
while (1) {
pthread_mutex_lock(&worker->pool->mtx);
// 没有任务则等待
while(worker->pool->jobs == NULL){
if (worker->terminate)
break;
pthread_cond_wait(&worker->pool->cond, &worker->pool->mtx);
}
// 执行任务
struct NJOB *job = worker->pool->jobs;
if(job != NULL){
LL_REMOVE(job, worker->pool->jobs);
}
pthread_mutex_unlock(&worker->pool->mtx);
job->func(job->user_data, worker->id);
}
free(worker);
pthread_exit(NULL);
}
// SDK
int nThreadPoolCreate