学习目标:
Linux
linux应用开发(高级编程):
(1)数据存储问题:文件和数据库
(2)多任务编程:进程 和 线程
(3)网络编程:tcp udp
学习内容:
线程池
学习时间:7.13.2024
学习产出:
.C文件
#include "pthread_dynamic_bigwater.h"
#include "queue.h"//自己写的队列函数
/*************************
函数名:create_threadpool
功能:线程池创建
参数:int threads,int queue_length
返回值:struct threadPool*
*************************/
struct threadPool* create_threadpool(int threads,int queue_length)
{
int ret = 0;
struct threadPool*pool = NULL;
pool = malloc(sizeof(POOL));
pool->tid = malloc(sizeof(pthread_t)*threads);
memset(pool->tid,0,sizeof(pthread_t)*threads);
pool->threads = threads;
pool->queue_length = queue_length;
//信号量定义并初始化
sem_init(&pool->semw,0,queue_length);
sem_init(&pool->semr,0,0);
//定义并初始化锁
pthread_mutex_init(&pool->mutex,NULL);
//队列创建
pool->que = create_queue();
for(int i = 0;i < threads;i++)
{
//创建n个消费者线程
ret = pthread_create((pool->tid) + i,NULL,fun2,pool);
if(ret != 0)
{
perror("pthread_create");
exit(-1);
}
}
return pool;
}
/*************************
函数名:destroy_threadPool
功能:销毁线程池
参数:struct threadPool* pool
返回值:无
*************************/
void destroy_threadPool(struct threadPool* pool)
{
POOL* dat = pool;
sem_post(&dat->semw);
//生产者线程结束
pthread_join(dat->tid_write,NULL);
//消费者线程结束
for(int i = 0;i < dat->threads;i++)
{
sem_post(&dat->semw);
sem_post(&dat->semr);
pthread_join(dat->tid[i],NULL);
}
//释放信号量
sem_destroy(&dat->semw);
sem_destroy(&dat->semr);
//销毁锁
pthread_mutex_destroy(&dat->mutex);
//销毁队列
queue_release(dat->que);
//释放tid空间
free(dat->tid);
//释放结构体空间
free(dat);
}
.H文件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include "queue.h"
typedef struct threadPool
{
sem_t semw;
sem_t semr;
pthread_mutex_t mutex;
int queue_length;
int threads;
pthread_t *tid;
QUE* que;
}POOL;
struct threadPool* create_threadpool(int threads,int queue_length);
void destroy_threadPool(struct threadPool* pool);