一、代码
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
struct worker
{
void* (*thread_proc)(void* arg);
void* arg;
struct worker* next;
};
struct thread_pool
{
struct worker* head;
int worker_num;
pthread_mutex_t mutex;
pthread_cond_t cond;
int thread_num;
pthread_t* tid;
int shutdown_flag;
};
struct thread_pool* g_pool = NULL;
void* process(void* arg)
{
struct worker* pworker = NULL;
while (1)
{
pthread_mutex_lock(&g_pool->mutex);
while(g_pool->head == NULL && 0 == g_pool->shutdown_flag)
pthread_cond_wait(&g_pool->cond, &g_pool->mutex);
if (g_pool->shutdown_flag)
{
pthread_mutex_unlock(&g_pool->mutex);
return (void*)1;
}
pworker = g_pool->head;
g_pool->head = pworker->next;
g_pool->worker_num--;
pthread_mutex_unlock(&g_pool->mutex);
(*(pworker->thread_proc))(pworker->arg);
}
return (void*)1;
}
int thread_pool_init(int thread_num)
{
g_pool = malloc(sizeof(struct thread_pool));
if (g_pool == NULL)
return -1;
g_pool->head = NULL;
g_pool->worker_num = 0;
pthread_mutex_init(&g_pool->mutex, NULL);
pthread_cond_init(&g_pool->cond, NULL);
g_pool->thread_num = thread_num;
g_pool->tid = malloc(sizeof(pthread_t) * g_pool->thread_num);
if (g_pool->tid == NULL)
{
free(g_pool);
g_pool = NULL;
return -2;
}
int i;
for (i=0; i<g_pool->thread_num; i++)
pthread_create(&g_pool->tid[i], NULL, process, NULL);
g_pool->shutdown_flag = 0;
return 0;
}
int thread_pool_destroy()
{
if (!g_pool)
return -1;
if (g_pool->shutdown_flag)
return -2;
g_pool->shutdown_flag = 1;
pthread_cond_broadcast(&g_pool->cond);
int i;
for (i=0; i<g_pool->thread_num; i++)
pthread_join(g_pool->tid[i], NULL);
free(g_pool->tid);
pthread_mutex_destroy(&g_pool->mutex);
pthread_cond_destroy(&g_pool->cond);
struct worker* pworker = NULL;
while (g_pool->head)
{
pworker = g_pool->head;
g_pool->head = pworker->next;
free(pworker);
}
free(g_pool);
g_pool = NULL;
return 0;
}
int thread_pool_add_worker(void* (*thread_proc)(void* arg), void* arg)
{
struct worker* pworker = malloc(sizeof(struct worker));
pworker->thread_proc = thread_proc;
pworker->arg = arg;
pworker->next = NULL;
pthread_mutex_lock(&g_pool->mutex);
pworker->next = g_pool->head;
g_pool->head = pworker;
g_pool->worker_num++;
pthread_mutex_unlock(&g_pool->mutex);
pthread_cond_signal(&g_pool->cond);
return 0;
}
void* myprocess(void* arg)
{
printf("thread 0x%x run on task %d\n", pthread_self(), *(int*)arg);
sleep(1);
return NULL;
}
int main(int argc, char* argv[])
{
int i;
int *num = malloc(sizeof(int)*10);
thread_pool_init(3);
for(i=0;i<10;i++)
{
num[i] = i;
thread_pool_add_worker(myprocess, &num[i]);
}
sleep(5);
free(num);
thread_pool_destroy();
return 0;
}
二、运行结果
3个线程,10个任务。