【原创】TCP Socket 简单练习 --- 线程池实现并发服务器
服务器函数执行流程
main
init_system
creat_pthread_pool
child_work
thread_manager
task_manager
process_client
monitor
sys_clean
Makefile文件
CC = gcc
TARGET = pthread_pool
SRC = pthread_pool.c base.c
OBJECT = pthread_pool.o base.o
INCLUDES = -I./
LDFLAGS = -lpthread
all:$(TARGET)
$(OBJECT):$(SRC)
$(CC) -c $(INCLUDES) ${SRC}
$(TARGET):$(OBJECT)
$(CC) -o $@ $(OBJECT) $(LDFLAGS)
.PHONY:clean
clean:
@rm -rf $(OBJECT) $(TARGET) *~
服务器代码
头文件
#ifndef __PTHREAD_POOL_H__
#define __PTHREAD_POOL_H__
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <assert.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <errno.h>
#define THREAD_MAX_NUM 100 /* max number of thread. */
#define THREAD_DEF_NUM 20 /* by default ,number of thread. */
#define THREAD_MIN_NUM 5 /* min number of thread pool. */
#define LISNUM<span style="white-space:pre"> </span>5
#define PORT 9001
#define MAXBUF 1024
/*
* *ds of the every task. make all task in a single link
*/
//任务结构节点,用于描述每个任务的具体属性
typedef struct task_node
{
void *arg; /* fun arg. */
void *(*fun)(void *); /* the real work of the task. */
pthread_t tid; /* which thread exec this task. */
int work_id; /* task id. */
int flag; /* 1: assigned, 0: unassigned. */
struct task_node *next;
pthread_mutex_t mutex; /* when modify this ds and exec the work,lock the task ds. */
} TASK_NODE;
/*
* *the ds of the task_queue
*/
//任务队列结构,用于控制整个任务队列
typedef struct task_queue
{
pthread_mutex_t mutex;
pthread_cond_t cond; /* when no task, the manager thread wait for ;when a new task come, signal. */
struct task_node *head; /* point to the task_link. */
int number; /* current number of task, include unassinged and assigned but no finished. */
} TASK_QUEUE_T;
/*
* *the ds of every thread, make all thread in a double link queue.
*/
//线程结构节点,用于描述每个线程的具体属性
typedef struct pthread_node
{
pthread_t tid; /* the pid of this thread in kernel,the value is syscall return . */
int flag; /* 1:busy, 0:free. */
struct task_node *work; /* if exec a work, which work. */
struct pthread_node *next;
struct pthread_node *prev;
pthread_cond_t cond; /* when assigned a task, signal this child thread by manager. */
pthread_mutex_t mutex;
} THREAD_NODE;
/*
* *the ds of the thread queue
*/
//线程队列结