设为首页 加入收藏

TOP

一个线程池的简单的实现(二)
2015-07-24 07:07:49 来源: 作者: 【 】 浏览:112
Tags:一个 线程 池的 简单 实现
out\n", (int)pthread_self());
timeout = 1;
break;
}
}


// 等待到条件,处于工作状态
pool->idle--;


// 等待到任务
if (pool->first != NULL)
{
// 从队头取出任务
task_t *t = pool->first;
pool->first = t->next;
// 执行任务需要一定的时间,所以要先解锁,以便生产者进程
// 能够往队列中添加任务,其它消费者线程能够进入等待任务
condition_unlock(&pool->ready);
t->run(t->arg);
free(t);
condition_lock(&pool->ready);
}
// 如果等待到线程池销毁通知, 且任务都执行完毕
if (pool->quit && pool->first == NULL)
{
pool->counter--;
if (pool->counter == 0)
condition_signal(&pool->ready);


condition_unlock(&pool->ready);
// 跳出循环之前要记得解锁
break;
}


if (timeout && pool->first == NULL)
{
pool->counter--;
condition_unlock(&pool->ready);
// 跳出循环之前要记得解锁
break;
}
condition_unlock(&pool->ready);
}


printf("thread 0x%x is exting\n", (int)pthread_self());
return NULL;


}


// 初始化线程池
void threadpool_init(threadpool_t *pool, int threads)
{
// 对线程池中的各个字段初始化
condition_init(&pool->ready);
pool->first = NULL;
pool->last = NULL;
pool->counter = 0;
pool->idle = 0;
pool->max_threads = threads;
pool->quit = 0;
}


// 往线程池中添加任务
void threadpool_add_task(threadpool_t *pool, void *(*run)(void *arg), void *arg)
{
// 生成新任务
task_t *newtask = (task_t *)malloc(sizeof(task_t));
newtask->run = run;
newtask->arg = arg;
newtask->next = NULL;


condition_lock(&pool->ready);
// 将任务添加到队列
if (pool->first == NULL)
pool->first = newtask;
else
pool->last->next = newtask;
pool->last = newtask;


// 如果有等待线程,则唤醒其中一个
if (pool->idle > 0)
condition_signal(&pool->ready);
else if (pool->counter < pool->max_threads)
{
// 没有等待线程,并且当前线程数不超过最大线程数,则创建一个新线程
pthread_t tid;
pthread_create(&tid, NULL, thread_routine, pool);
pool->counter++;
}
condition_unlock(&pool->ready);
}


// 销毁线程池
void threadpool_destroy(threadpool_t *pool)
{
if (pool->quit)
{
return;
}
condition_lock(&pool->ready);
pool->quit = 1;
if (pool->counter > 0)
{
if (pool->idle > 0)
condition_broadcast(&pool->ready);


// 处于执行任务状态中的线程,不会收到广播
// 线程池需要等待执行任务状态中的线程全部退出


while (pool->counter > 0)
condition_wait(&pool->ready);
}
condition_unlock(&pool->ready);
condition_destroy(&pool->ready);




}

main.c #include "threadpool.h"
#include
#include
#include


void* mytask(void *arg)
{
printf("thread 0x%x is working on task %d\n", (int)pthread_self(), *(int*)arg);
sleep(1);
free(arg);
return NULL;
}


int main(void)
{
threadpool_t pool;
threadpool_init(&pool, 3);


int i;
for (i=0; i<10; i++)
{
int *arg = (int *)malloc(sizeof(int));
*arg = i;
threadpool_add_task(&pool, mytask, arg);
}


//sleep(15);
threadpool_destroy(&pool);
return 0;
}

makefile: .PHONY:clean
CC=gcc
CFLAGS=-Wall -g
ALL=main
all:$(ALL)
OBJS=threadpool.o main.o condition.o
.c.o:
$(CC) $(CFLAGS) -c $<


main:$(OBJS)
$(CC) $(CFLAGS) $^ -o $@ -lpthread -lrt


clean:
rm -f $(ALL) *.o

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇用二叉链表实现二叉查找树(二) 下一篇C++编译与链接(1)-编译与链接过..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: