linux线程池示例

来源:互联网 发布:女性生殖健康 知乎 编辑:程序博客网 时间:2024/04/30 12:22

吐舌头池类封装:

/*************************************************************************> File Name: tpool.h> Author: XXDK> Email: v.manstein@qq.com > Created Time: Thu 16 Mar 2017 06:17:34 PM PDT ************************************************************************/#ifndef _TPOOL_H#define _TPOOL_H#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <unistd.h>typedef struct task {void* (*func)(void*);void* arg;struct task* next;}task_t;typedef struct tpool {pthread_mutex_t mutex;pthread_cond_t cond;task_t *mytask;// 任务队列的队头pthread_t *tid;// 线程id的指针}tpool_t;tpool_t* create_tpool(int num);int tpool_add_task(tpool_t *tp, void* (*func)(void*), void *arg);#endif // _TPOOL_H

吐舌头方法实现

/*************************************************************************> File Name: tpool.c> Author: XXDK> Email: v.manstein@qq.com > Created Time: Thu 16 Mar 2017 06:29:57 PM PDT ************************************************************************/#include "tpool.h"static void *do_task(void* arg){tpool_t *tp = (tpool_t*)arg;while(1) {// 操作共享数据,加锁避免竞态pthread_mutex_lock(&tp->mutex);// 查看条件(任务链中是否有待处理的任务)while(tp->mytask == NULL) {// 任务链为空,解锁,加入等待队列,休眠,等待唤醒pthread_cond_wait(&tp->cond, &tp->mutex);}// 摘取任务节点task_t *tmp = tp->mytask;tp->mytask = tmp->next;// 任务摘取完,解锁pthread_mutex_unlock(&tp->mutex);// 执行取到节点的任务tmp->func(tmp->arg);free(tmp);}}// 创建一个线程池对象tpool_t* create_tpool(int num){tpool_t *tp = (tpool_t*)malloc(sizeof(tpool_t));// 线程池对象初始化pthread_mutex_init(&tp->mutex, NULL);pthread_cond_init(&tp->cond, NULL);tp->mytask = NULL;tp->tid = (pthread_t*)malloc(sizeof(pthread_t)*num); // 在该线程池中创建num个线程,传入任务处理接口while(num--) {pthread_create(&tp->tid[num], NULL, do_task, tp);}return tp;}// 往某个线程池对象添加任务(线程池对象初始化)// @tp 往哪个线程池添加任务// @func 传入具体任务int tpool_add_task(tpool_t* tp, void *(*func)(void*), void *arg){task_t* newtask = (task_t*)malloc(sizeof(task_t));newtask->func = func;newtask->arg = arg;newtask->next = NULL;// 含任务func的节点插入任务链中,避免竞态pthread_mutex_lock(&tp->mutex);newtask->next = tp->mytask;tp->mytask = newtask;pthread_mutex_unlock(&tp->mutex);// 任务添加完毕,广播条件(有新任务加入任务链)pthread_cond_broadcast(&tp->cond);return 1;}

吐舌头测试函数

/*************************************************************************> File Name: test.c> Author: XXDK> Email: v.manstein@qq.com > Created Time: Thu 16 Mar 2017 06:51:38 PM PDT ************************************************************************/#include "tpool.h"void *thread_func(void* arg){printf("[%lu]: %d\n", pthread_self(), (int)arg);sleep(1);}int main(){tpool_t* tp = create_tpool(10);int n = 1000;while(n--) {tpool_add_task(tp, thread_func, (void*)n);}pause();return 0;}






0 0