linux服务器开发 2019.2.7(libevent实现http server,线程池)
libevent实现http server libevent在获取到文件描述符之后有两种选择struct event* ev=event_new(base, fd, ev_read, callback, arg);struct* bufferevent = bufferevent_socket_new(base, fd, )BEV_OPT_CLOSE_ON_FREE); ma...
·
libevent实现http server
libevent在获取到文件描述符之后有两种选择
- struct event* ev=event_new(base, fd, ev_read, callback, arg);
- struct* bufferevent = bufferevent_socket_new(base, fd, )BEV_OPT_CLOSE_ON_FREE);
main.c
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <event2/bufferevent.h>
#include <event2/listener.h>
#include <event2/event.h>
#include "libevent_http.h"
int main(int argc, char **argv) {
if(argc < 3){
printf("./event_http port path\n");
return -1;
}
if(chdir(argv[2]) < 0) {
printf("dir is not exists: %s\n", argv[2]);
perror("chdir err:");
return -1;
}
struct event_base *base; //事件处理框架
struct evconnlistener *listener;
struct event *signal_event;
struct sockaddr_in sin;
//事件处理框架,不带buffer的
base = event_base_new();
if (!base){
fprintf(stderr, "Could not initialize libevent!\n");
return 1;
}
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(atoi(argv[1]));
// 创建监听的套接字,绑定,监听,接受连接请求
//evconnlistener_new_bind函数传入的参数,从左到右依次是:
//事件处理框架,回调函数,回调函数的参数,bind的属性(端口复用 and 关闭连接之后自动释放资源,不释放listener),
//backlog最大值,本地IP和端口,结构体大小
listener = evconnlistener_new_bind(base, listener_cb, (void *)base,
LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, -1,
(struct sockaddr*)&sin, sizeof(sin));
if (!listener){
fprintf(stderr, "Could not create a listener!\n");
return 1;
}
// 创建信号事件, 捕捉并处理
//evsignal_new给对应的信号设置事件
signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base);
//实践创建成功并且添加成功时
if (!signal_event || event_add(signal_event, NULL)<0) {
fprintf(stderr, "Could not create/add a signal event!\n");
return 1;
}
// 事件循环
event_base_dispatch(base);
evconnlistener_free(listener);
event_free(signal_event);
event_base_free(base);
printf("done\n");
return 0;
}
libevent_http.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <string.h>
#include <dirent.h>
#include <time.h>
#include <signal.h>
#include <ctype.h>
#include <errno.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include "libevent_http.h"
#define _HTTP_CLOSE_ "Connection: close\r\n"
int response_http(struct bufferevent *bev, const char *method, char *path){
if(strcasecmp("GET", method) == 0){
//get method ...
strdecode(path, path);
char *pf = &path[1];
if(strcmp(path, "/") == 0 || strcmp(path, "/.") == 0) {
pf="./";
}
printf("***** http Request Resource Path = %s, pf = %s\n", path, pf);
struct stat sb;
if(stat(pf,&sb) < 0){
perror("open file err:");
send_error(bev);
return -1;
}
//处理目录
if(S_ISDIR(sb.st_mode)) {
//应该显示目录列表
send_header(bev, 200, "OK", get_file_type(".html"), -1);
send_dir(bev, pf);
}
//处理文件
else {
send_header(bev, 200, "OK", get_file_type(pf), sb.st_size);
send_file_to_http(pf, bev);
}
}
return 0;
}
/*
*charset=iso-8859-1 西欧的编码,说明网站采用的编码是英文;
*charset=gb2312 说明网站采用的编码是简体中文;
*charset=utf-8 代表世界通用的语言编码;
* 可以用到中文、韩文、日文等世界上所有语言编码上
*charset=euc-kr 说明网站采用的编码是韩文;
*charset=big5 说明网站采用的编码是繁体中文;
*
*以下是依据传递进来的文件名,使用后缀判断是何种文件类型
*将对应的文件类型按照http定义的关键字发送回去
*/
const char *get_file_type(char *name){
char* dot;
dot = strrchr(name, '.'); //自右向左查找‘.’字符;如不存在返回NULL
if (dot == (char*)0)
return "text/plain; charset=utf-8";
if (strcmp(dot, ".html") == 0 || strcmp(dot, ".htm") == 0)
return "text/html; charset=utf-8";
if (strcmp(dot, ".jpg") == 0 || strcmp(dot, ".jpeg") == 0)
return "image/jpeg";
if (strcmp(dot, ".gif") == 0)
return "image/gif";
if (strcmp(dot, ".png") == 0)
return "image/png";
if (strcmp(dot, ".css") == 0)
return "text/css";
if (strcmp(dot, ".au") == 0)
return "audio/basic";
if (strcmp( dot, ".wav") == 0)
return "audio/wav";
if (strcmp(dot, ".avi") == 0)
return "video/x-msvideo";
if (strcmp(dot, ".mov") == 0 || strcmp(dot, ".qt") == 0)
return "video/quicktime";
if (strcmp(dot, ".mpeg") == 0 || strcmp(dot, ".mpe") == 0)
return "video/mpeg";
if (strcmp(dot, ".vrml") == 0 || strcmp(dot, ".wrl") == 0)
return "model/vrml";
if (strcmp(dot, ".midi") == 0 || strcmp(dot, ".mid") == 0)
return "audio/midi";
if (strcmp(dot, ".mp3") == 0)
return "audio/mpeg";
if (strcmp(dot, ".ogg") == 0)
return "application/ogg";
if (strcmp(dot, ".pac") == 0)
return "application/x-ns-proxy-autoconfig";
return "text/plain; charset=utf-8";
}
int send_file_to_http(const char *filename, struct bufferevent *bev){
int fd = open(filename, O_RDONLY);
int ret = 0;
char buf[4096] = {0};
while( (ret = read(fd, buf, sizeof(buf)) ) ){
bufferevent_write(bev, buf, ret);
memset(buf, 0, ret);
}
close(fd);
return 0;
}
int send_header(struct bufferevent *bev, int no, const char* desp, const char *type, long len){
char buf[256]={0};
sprintf(buf, "HTTP/1.1 %d %s\r\n", no, desp);
//HTTP/1.1 200 OK\r\n
bufferevent_write(bev, buf, strlen(buf));
// 文件类型
sprintf(buf, "Content-Type:%s\r\n", type);
bufferevent_write(bev, buf, strlen(buf));
// 文件大小
sprintf(buf, "Content-Length:%ld\r\n", len);
bufferevent_write(bev, buf, strlen(buf));
// Connection: close
bufferevent_write(bev, _HTTP_CLOSE_, strlen(_HTTP_CLOSE_));
//send \r\n
bufferevent_write(bev, "\r\n", 2);
return 0;
}
int send_error(struct bufferevent *bev) {
send_header(bev,404, "File Not Found", "text/html", -1);
send_file_to_http("404.html", bev);
return 0;
}
int send_dir(struct bufferevent *bev,const char *dirname){
char encoded_name[1024];
char path[1024];
char timestr[64];
struct stat sb;
struct dirent **dirinfo;
char buf[4096] = {0};
sprintf(buf, "<html><head><meta charset=\"utf-8\"><title>%s</title></head>", dirname);
sprintf(buf+strlen(buf), "<body><h1>当前目录:%s</h1><table>", dirname);
//添加目录内容
int num = scandir(dirname, &dirinfo, NULL, alphasort);
for(int i=0; i<num; ++i){
// 编码
strencode(encoded_name, sizeof(encoded_name), dirinfo[i]->d_name);
sprintf(path, "%s%s", dirname, dirinfo[i]->d_name);
printf("############# path = %s\n", path);
if (lstat(path, &sb) < 0){
sprintf(buf+strlen(buf),
"<tr><td><a href=\"%s\">%s</a></td></tr>\n",
encoded_name, dirinfo[i]->d_name);
} else {
strftime(timestr, sizeof(timestr),
" %d %b %Y %H:%M", localtime(&sb.st_mtime));
if(S_ISDIR(sb.st_mode)){
sprintf(buf+strlen(buf),
"<tr><td><a href=\"%s/\">%s/</a></td><td>%s</td><td>%ld</td></tr>\n",
encoded_name, dirinfo[i]->d_name, timestr, sb.st_size);
} else {
sprintf(buf+strlen(buf),
"<tr><td><a href=\"%s\">%s</a></td><td>%s</td><td>%ld</td></tr>\n",
encoded_name, dirinfo[i]->d_name, timestr, sb.st_size);
}
}
bufferevent_write(bev, buf, strlen(buf));
memset(buf, 0, sizeof(buf));
}
sprintf(buf+strlen(buf), "</table></body></html>");
bufferevent_write(bev, buf, strlen(buf));
printf("################# Dir Read OK !!!!!!!!!!!!!!\n");
return 0;
}
void conn_readcb(struct bufferevent *bev, void *user_data){
printf("******************** begin call %s.........\n",__FUNCTION__);
char buf[4096]={0};
char method[50], path[4096], protocol[32];
bufferevent_read(bev, buf, sizeof(buf));
printf("buf[%s]\n", buf);
sscanf(buf, "%[^ ] %[^ ] %[^ \r\n]", method, path, protocol);
printf("method[%s], path[%s], protocol[%s]\n", method, path, protocol);
if(strcasecmp(method, "GET") == 0){
response_http(bev, method, path);
}
printf("******************** end call %s.........\n", __FUNCTION__);
}
void conn_eventcb(struct bufferevent *bev, short events, void *user_data){
printf("******************** begin call %s.........\n", __FUNCTION__);
if (events & BEV_EVENT_EOF){
printf("Connection closed.\n");
}
else if (events & BEV_EVENT_ERROR){
printf("Got an error on the connection: %s\n",
strerror(errno));
}
bufferevent_free(bev);
printf("******************** end call %s.........\n", __FUNCTION__);
}
void signal_cb(evutil_socket_t sig, short events, void *user_data){
struct event_base *base = user_data;
struct timeval delay = { 1, 0 };
printf("Caught an interrupt signal; exiting cleanly in one seconds.\n");
event_base_loopexit(base, &delay);
}
//fd是用于通信的文件描述符
void listener_cb(struct evconnlistener *listener,
evutil_socket_t fd, struct sockaddr *sa, int socklen, void *user_data){
printf("******************** begin call-------%s\n",__FUNCTION__);
struct event_base *base = user_data;
struct bufferevent *bev;
printf("fd is %d\n",fd);
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
if (!bev){
fprintf(stderr, "Error constructing bufferevent!");
event_base_loopbreak(base);
return;
}
//强制性把缓冲区里面的数据刷出去
bufferevent_flush(bev, EV_READ | EV_WRITE, BEV_NORMAL);
bufferevent_setcb(bev, conn_readcb, NULL, conn_eventcb, NULL);
//启用写回调和读回调
bufferevent_enable(bev, EV_READ | EV_WRITE);
printf("******************** end call-------%s\n",__FUNCTION__);
}
/*
* 这里的内容是处理%20之类的东西!是"解码"过程。
* %20 URL编码中的‘ ’(space)
* %21 '!' %22 '"' %23 '#' %24 '$'
* %25 '%' %26 '&' %27 ''' %28 '('......
* 相关知识html中的‘ ’(space)是 
*/
void strdecode(char *to, char *from){
for ( ; *from != '\0'; ++to, ++from) {
if (from[0] == '%' && isxdigit(from[1]) && isxdigit(from[2])){
// 依次判断from中 %20 三个字符
*to = hexit(from[1])*16 + hexit(from[2]);
// 移过已经处理的两个字符(%21指针指向1),表达式3的++from还会再向后移一个字符
from += 2;
} else {
*to = *from;
}
}
*to = '\0';
}
//16进制数转化为10进制, return 0不会出现
int hexit(char c){
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return 0;
}
// "编码",用作回写浏览器的时候,将除字母数字及/_.-~以外的字符转义后回写。
// strencode(encoded_name, sizeof(encoded_name), name);
void strencode(char* to, size_t tosize, const char* from){
int tolen;
for (tolen = 0; *from != '\0' && tolen + 4 < tosize; ++from){
if (isalnum(*from) || strchr("/_.-~", *from) != (char*)0){
*to = *from;
++to;
++tolen;
} else {
sprintf(to, "%%%02x", (int) *from & 0xff);
to += 3;
tolen += 3;
}
}
*to = '\0';
}
libevent_http.h
#ifndef _LIBEVENT_HTTP_H
#define _LIBEVENT_HTTP_H
#include <event2/event.h>
void conn_eventcb(struct bufferevent *bev, short events, void *user_data);
void conn_readcb(struct bufferevent *bev, void *user_data);
const char *get_file_type(char *name);
int hexit(char c);
void listener_cb(struct evconnlistener *listener, evutil_socket_t fd,
struct sockaddr *sa, int socklen, void *user_data);
int response_http(struct bufferevent *bev, const char *method, char *path);
int send_dir(struct bufferevent *bev,const char *dirname);
int send_error(struct bufferevent *bev);
int send_file_to_http(const char *filename, struct bufferevent *bev);
int send_header(struct bufferevent *bev, int no, const char* desp, const char *type, long len);
void signal_cb(evutil_socket_t sig, short events, void *user_data);
void strdecode(char *to, char *from);
void strencode(char* to, size_t tosize, const char* from);
#endif
线程池
线程池要处理任务,任务的个数不定。因此线程池中存在两种线程:
- 管理线程——不处理任务——不直接杀死线程,而是让线程自杀
- 工作线程——只处理任务
什么时候创建线程
- 每隔一段时间去判断,如果工作的线程超过85%,则创建新线程(可以指定创建多少个)
什么时候销毁线程
- 每隔一段时间去判断,如果工作的线程小于20%(值都是自己设定的)
线程池结构体
typedef struct {
void *(*function)(void *); /* 函数指针,回调函数 */
void *arg; /* 上面函数的参数 */
} threadpool_task_t; /* 各子线程任务结构体 */
/* 描述线程池相关信息 */
struct threadpool_t {
pthread_mutex_t lock; /* 用于锁住本结构体 */
pthread_mutex_t thread_counter; /* 记录忙状态线程个数de琐 -- busy_thr_num */
pthread_cond_t queue_not_full; /* 当任务队列满时,添加任务的线程阻塞,等待此条件变量 */
pthread_cond_t queue_not_empty; /* 任务队列里不为空时,通知等待任务的线程 */
pthread_t *threads; /* 存放线程池中每个线程的tid。数组 */
pthread_t adjust_tid; /* 存管理线程tid */
threadpool_task_t *task_queue; /* 任务队列 */
int min_thr_num; /* 线程池最小线程数 */
int max_thr_num; /* 线程池最大线程数 */
int live_thr_num; /* 当前存活线程个数 */
int busy_thr_num; /* 忙状态线程个数 */
int wait_exit_thr_num; /* 要销毁的线程个数 */
int queue_front; /* task_queue队头下标 */
int queue_rear; /* task_queue队尾下标 */
int queue_size; /* task_queue队中实际任务数 */
int queue_max_size; /* task_queue队列可容纳任务数上限 */
int shutdown; /* 标志位,线程池使用状态,true或false */
};
如何使用线程池
int main(void) {
//创建线程池,池里最小3个线程,最大100,任务队列最多放100个任务
/*threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);*/
threadpool_t *thp = threadpool_create(3,100,100);
printf("pool inited");
//int *num = (int *)malloc(sizeof(int)*20);
int num[20], i;
for (i = 0; i < 20; i++) {
num[i]=i;
printf("add task %d\n",i);
//(void*)&num[i]给回调函数process传参
threadpool_add(thp, process, (void*)&num[i]); /* 向线程池中添加任务 */
}
sleep(10); /* 等子线程完成任务 */
threadpool_destroy(thp);
return 0;
}
线程池完整代码
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
#include "threadpool.h"
#define DEFAULT_TIME 10 /*10s检测一次*/
#define MIN_WAIT_TASK_NUM 10 /*如果queue_size > MIN_WAIT_TASK_NUM 添加新的线程到线程池*/
#define DEFAULT_THREAD_VARY 10 /*每次创建和销毁线程的个数*/
#define true 1
#define false 0
typedef struct {
void *(*function)(void *); /* 函数指针,回调函数 */
void *arg; /* 上面函数的参数 */
} threadpool_task_t; /* 各子线程任务结构体 */
/* 描述线程池相关信息 */
struct threadpool_t {
pthread_mutex_t lock; /* 用于锁住本结构体 */
pthread_mutex_t thread_counter; /* 记录忙状态线程个数de琐 -- busy_thr_num */
pthread_cond_t queue_not_full; /* 当任务队列满时,添加任务的线程阻塞,等待此条件变量 */
pthread_cond_t queue_not_empty; /* 任务队列里不为空时,通知等待任务的线程 */
pthread_t *threads; /* 存放线程池中每个线程的tid。数组 */
pthread_t adjust_tid; /* 存管理线程tid */
threadpool_task_t *task_queue; /* 任务队列 */
int min_thr_num; /* 线程池最小线程数 */
int max_thr_num; /* 线程池最大线程数 */
int live_thr_num; /* 当前存活线程个数 */
int busy_thr_num; /* 忙状态线程个数 */
int wait_exit_thr_num; /* 要销毁的线程个数 */
int queue_front; /* task_queue队头下标 */
int queue_rear; /* task_queue队尾下标 */
int queue_size; /* task_queue队中实际任务数 */
int queue_max_size; /* task_queue队列可容纳任务数上限 */
int shutdown; /* 标志位,线程池使用状态,true或false */
};
/**
* @function void *threadpool_thread(void *threadpool)
* @desc the worker thread
* @param threadpool the pool which own the thread
*/
void *threadpool_thread(void *threadpool);
/**
* @function void *adjust_thread(void *threadpool);
* @desc manager thread
* @param threadpool the threadpool
*/
void *adjust_thread(void *threadpool);
/**
* check a thread is alive
*/
int is_thread_alive(pthread_t tid);
int threadpool_free(threadpool_t *pool);
threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size){
int i;
threadpool_t *pool = NULL;
//do while(0) 技巧
do {
if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) {
printf("malloc threadpool fail");
break;/*跳出do while*/
}
pool->min_thr_num = min_thr_num;
pool->max_thr_num = max_thr_num;
pool->busy_thr_num = 0;
pool->live_thr_num = min_thr_num; /* 活着的线程数 初值=最小线程数 */
pool->queue_size = 0; /* 有0个产品 */
pool->queue_max_size = queue_max_size;
pool->queue_front = 0;
pool->queue_rear = 0;
pool->shutdown = false; /* 不关闭线程池 */
/* 根据最大线程上限数, 给工作线程数组开辟空间, 并清零 */
pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num);
if (pool->threads == NULL) {
printf("malloc threads fail");
break;
}
memset(pool->threads, 0, sizeof(pthread_t)*max_thr_num);
/* 队列开辟空间 */
pool->task_queue = (threadpool_task_t *)malloc(sizeof(threadpool_task_t)*queue_max_size);
if (pool->task_queue == NULL) {
printf("malloc task_queue fail");
break;
}
/* 初始化互斥琐、条件变量 */
if (pthread_mutex_init(&(pool->lock), NULL) != 0
|| pthread_mutex_init(&(pool->thread_counter), NULL) != 0
|| pthread_cond_init(&(pool->queue_not_empty), NULL) != 0
|| pthread_cond_init(&(pool->queue_not_full), NULL) != 0) {
printf("init the lock or cond fail");
break;
}
/* 启动 min_thr_num 个 work thread */
for (i = 0; i < min_thr_num; i++) {
pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);/*pool指向当前线程池*/
printf("start thread 0x%x...\n", (unsigned int)pool->threads[i]);
}
pthread_create(&(pool->adjust_tid), NULL, adjust_thread, (void *)pool);/* 启动管理者线程 */
return pool;
} while (0);
threadpool_free(pool); /* 前面代码调用失败时,释放poll存储空间 */
return NULL;
}
/* 向线程池中 添加一个任务 */
int threadpool_add(threadpool_t *pool, void*(*function)(void *arg), void *arg){
pthread_mutex_lock(&(pool->lock));
/* ==为真,队列已经满, 调wait阻塞 */
while ((pool->queue_size == pool->queue_max_size) && (!pool->shutdown)) {
pthread_cond_wait(&(pool->queue_not_full), &(pool->lock));
}
if (pool->shutdown) {
pthread_mutex_unlock(&(pool->lock));
}
/* 清空 工作线程 调用的回调函数 的参数arg */
if (pool->task_queue[pool->queue_rear].arg != NULL) {
free(pool->task_queue[pool->queue_rear].arg);
pool->task_queue[pool->queue_rear].arg = NULL;
}
/*添加任务到任务队列里*/
pool->task_queue[pool->queue_rear].function = function;
pool->task_queue[pool->queue_rear].arg = arg;
pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size; /* 队尾指针移动, 模拟环形 */
pool->queue_size++;
/*添加完任务后,队列不为空,唤醒线程池中 等待处理任务的线程*/
pthread_cond_signal(&(pool->queue_not_empty));
pthread_mutex_unlock(&(pool->lock));
return 0;
}
/* 线程池中各个工作线程 */
void *threadpool_thread(void *threadpool){
threadpool_t *pool = (threadpool_t *)threadpool;
threadpool_task_t task;
while (true) {
/* Lock must be taken to wait on conditional variable */
/*刚创建出线程,等待任务队列里有任务,否则阻塞等待任务队列里有任务后再唤醒接收任务*/
pthread_mutex_lock(&(pool->lock));
/*queue_size == 0 说明没有任务,调 wait 阻塞在条件变量上, 若有任务,跳过该while*/
while ((pool->queue_size == 0) && (!pool->shutdown)) {
printf("thread 0x%x is waiting\n", (unsigned int)pthread_self());
pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock));
/*清除指定数目的空闲线程,如果要结束的线程个数大于0,结束线程*/
if (pool->wait_exit_thr_num > 0) {
pool->wait_exit_thr_num--;
/*如果线程池里线程个数大于最小值时可以结束当前线程*/
if (pool->live_thr_num > pool->min_thr_num) {
printf("thread 0x%x is exiting\n", (unsigned int)pthread_self());
pool->live_thr_num--;
pthread_mutex_unlock(&(pool->lock));
pthread_exit(NULL);
}
}
}
/*如果指定了true,要关闭线程池里的每个线程,自行退出处理*/
if (pool->shutdown) {
pthread_mutex_unlock(&(pool->lock));
printf("thread 0x%x is exiting\n", (unsigned int)pthread_self());
pthread_exit(NULL); /* 线程自行结束 */
}
/*从任务队列里获取任务, 是一个出队操作*/
task.function = pool->task_queue[pool->queue_front].function;
task.arg = pool->task_queue[pool->queue_front].arg;
pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size; /* 出队,模拟环形队列 */
pool->queue_size--;
/*通知可以有新的任务添加进来*/
pthread_cond_broadcast(&(pool->queue_not_full));
/*任务取出后,立即将 线程池琐 释放*/
pthread_mutex_unlock(&(pool->lock));
/*执行任务*/
printf("thread 0x%x start working\n", (unsigned int)pthread_self());
pthread_mutex_lock(&(pool->thread_counter)); /*忙状态线程数变量琐*/
pool->busy_thr_num++; /*忙状态线程数+1*/
pthread_mutex_unlock(&(pool->thread_counter));
(*(task.function))(task.arg); /*执行回调函数任务*/
//task.function(task.arg); /*执行回调函数任务*/
/*任务结束处理*/
printf("thread 0x%x end working\n", (unsigned int)pthread_self());
pthread_mutex_lock(&(pool->thread_counter));
pool->busy_thr_num--; /*处理掉一个任务,忙状态数线程数-1*/
pthread_mutex_unlock(&(pool->thread_counter));
}
pthread_exit(NULL);
}
/* 管理线程 */
void *adjust_thread(void *threadpool){
int i;
threadpool_t *pool = (threadpool_t *)threadpool;
while (!pool->shutdown) {
sleep(DEFAULT_TIME); /*定时 对线程池管理*/
pthread_mutex_lock(&(pool->lock));
int queue_size = pool->queue_size; /* 关注 任务数 */
int live_thr_num = pool->live_thr_num; /* 存活 线程数 */
pthread_mutex_unlock(&(pool->lock));
pthread_mutex_lock(&(pool->thread_counter));
int busy_thr_num = pool->busy_thr_num; /* 忙着的线程数 */
pthread_mutex_unlock(&(pool->thread_counter));
/* 创建新线程 算法: 任务数大于最小线程池个数, 且存活的线程数少于最大线程个数时 如:30>=10 && 40<100*/
if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num < pool->max_thr_num) {
pthread_mutex_lock(&(pool->lock));
int add = 0;
/*一次增加 DEFAULT_THREAD 个线程*/
for (i = 0; i < pool->max_thr_num && add < DEFAULT_THREAD_VARY
&& pool->live_thr_num < pool->max_thr_num; i++) {
if (pool->threads[i] == 0 || !is_thread_alive(pool->threads[i])) {
pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);
add++;
pool->live_thr_num++;
}
}
pthread_mutex_unlock(&(pool->lock));
}
/* 销毁多余的空闲线程 算法:忙线程X2 小于 存活的线程数 且 存活的线程数 大于 最小线程数时*/
if ((busy_thr_num * 2) < live_thr_num && live_thr_num > pool->min_thr_num) {
/* 一次销毁DEFAULT_THREAD个线程, 隨機10個即可 */
pthread_mutex_lock(&(pool->lock));
pool->wait_exit_thr_num = DEFAULT_THREAD_VARY; /* 要销毁的线程数 设置为10 */
pthread_mutex_unlock(&(pool->lock));
for (i = 0; i < DEFAULT_THREAD_VARY; i++) {
/* 通知处在空闲状态的线程, 他们会自行终止*/
pthread_cond_signal(&(pool->queue_not_empty));
}
}
}
return NULL;
}
int threadpool_destroy(threadpool_t *pool){
int i;
if (pool == NULL) {
return -1;
}
pool->shutdown = true;
/*先销毁管理线程*/
pthread_join(pool->adjust_tid, NULL);
for (i = 0; i < pool->live_thr_num; i++) {
/*通知所有的空闲线程*/
pthread_cond_broadcast(&(pool->queue_not_empty));
}
for (i = 0; i < pool->live_thr_num; i++) {
pthread_join(pool->threads[i], NULL);
}
threadpool_free(pool);
return 0;
}
int threadpool_free(threadpool_t *pool){
if (pool == NULL) {
return -1;
}
if (pool->task_queue) {
free(pool->task_queue);
}
if (pool->threads) {
free(pool->threads);
pthread_mutex_lock(&(pool->lock));
pthread_mutex_destroy(&(pool->lock));
pthread_mutex_lock(&(pool->thread_counter));
pthread_mutex_destroy(&(pool->thread_counter));
pthread_cond_destroy(&(pool->queue_not_empty));
pthread_cond_destroy(&(pool->queue_not_full));
}
free(pool);
pool = NULL;
return 0;
}
int threadpool_all_threadnum(threadpool_t *pool){
int all_threadnum = -1;
pthread_mutex_lock(&(pool->lock));
all_threadnum = pool->live_thr_num;
pthread_mutex_unlock(&(pool->lock));
return all_threadnum;
}
int threadpool_busy_threadnum(threadpool_t *pool){
int busy_threadnum = -1;
pthread_mutex_lock(&(pool->thread_counter));
busy_threadnum = pool->busy_thr_num;
pthread_mutex_unlock(&(pool->thread_counter));
return busy_threadnum;
}
int is_thread_alive(pthread_t tid){
int kill_rc = pthread_kill(tid, 0); //发0号信号,测试线程是否存活
if (kill_rc == ESRCH) {
return false;
}
return true;
}
/*测试*/
#if 1
/* 线程池中的线程,模拟处理业务 */
void *process(void *arg){
printf("thread 0x%x working on task %d\n ",(unsigned int)pthread_self(),*(int *)arg);
sleep(1);
printf("task %d is end\n",*(int *)arg);
return NULL;
}
int main(void) {
//创建线程池,池里最小3个线程,最大100,任务队列最多放100个任务
/*threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);*/
threadpool_t *thp = threadpool_create(3,100,100);
printf("pool inited");
//int *num = (int *)malloc(sizeof(int)*20);
int num[20], i;
for (i = 0; i < 20; i++) {
num[i]=i;
printf("add task %d\n",i);
//(void*)&num[i]给回调函数process传参
threadpool_add(thp, process, (void*)&num[i]); /* 向线程池中添加任务 */
}
sleep(10); /* 等子线程完成任务 */
threadpool_destroy(thp);
return 0;
}
#endif
更多推荐
已为社区贡献1条内容
所有评论(0)