- 论坛徽章:
- 0
|
最近写的线程池公用开发库,带一个简单的测试代码,使用了队列进行线程分批。可以同时创建多个线程池。欢迎大家指点批正。
直接运行 make ,然后执行生成的 pools 测试程序。
下面是核心部分代码:
int pool_dispatch(pool* pl, void(*cb)(void*), void* arg)
{
pool_thread* thread;
pool_queue_item* item;
pthread_mutex_lock(&(pl->mutex));
if(0 == pl->idle_total)
{
pthread_mutex_unlock(&(pl->mutex));
return 2;
}
/* get from queue of idle threads */
pl->idle_total--;
item = pool_queue_get(pl->idle_threads);
if(NULL != item)
{
thread = (pool_thread*)item->data;
thread->cb = cb;
thread->arg = arg;
pthread_cond_signal(&(thread->cond));
}
pthread_mutex_unlock(&(pl->mutex));
return 0;
}
void* pool_warpper(void* arg)
{
pool_thread* thread = (pool_thread*)arg;
pool* pl = (pool*)thread->parent;
for(; 0 == pl->stop;)
{
pthread_mutex_lock(&(thread->mutex));
pthread_cond_wait(&(thread->cond), &(thread->mutex));
if((0 == pl->stop) && (NULL != thread->cb))
{
thread->cb(thread->arg);
}
pthread_mutex_unlock(&(thread->mutex));
/* put into queue of idle thread */
pthread_mutex_lock(&(pl->mutex));
pool_queue_put(pl->idle_threads, &(thread->queue));
pl->idle_total++;
pthread_mutex_unlock(&(pl->mutex));
}
return NULL;
} |
|
|