线程池原理详解及如何用C语言实现线程池( 四 )


if (pool->threads)
{
free(pool->threads);
pthread_mutex_lock(&(pool->lock)); /*先锁住再销毁*/
pthread_mutex_destroy(&(pool->lock));
pthread_mutex_lock(&(pool->thread_counter));
pthread_mutex_destroy(&(pool->thread_counter));
pthread_cond_destroy(&(pool->queue_not_empty));
pthread_cond_destroy(&(pool->queue_not_full));
}
free(pool);
pool = NULL;
return 0;
}

/*销毁线程池*/
int
threadpool_destroy(threadpool_t *pool)
{
int i;
if (pool == NULL)
{
return -1;
}
pool->shutdown = true;
/*销毁管理者线程*/
pthread_join(pool->admin_tid, NULL);
//通知所有线程去自杀(在自己领任务的过程中)
for (i=0; i<pool->live_thr_num; i++)
{
pthread_cond_broadcast(&(pool->queue_not_empty));
}
/*等待线程结束 先是pthread_exit 然后等待其结束*/
for (i=0; i<pool->live_thr_num; i++)
{
pthread_join(pool->threads[i], NULL);
}
threadpool_free(pool);
return 0;
}
六、接口
/* 线程池初始化 , 其管理者线程及工作线程都会启动 */
threadpool_t *thp = threadpool_create(10, 100, 100);
printf("threadpool init ... ... n");
/* 接收到任务后添加 */
threadpool_add_task(thp, do_work, (void *)p);
// ... ...
/* 销毁 */
threadpool_destroy(thp);
需要C/C++ linux服务器开发学习资料私信“资料”(资料包括C/C++ , Linux , golang技术 , Nginx , ZeroMQ , MySQL , redis , fastdfs , MongoDB , ZK , 流媒体 , CDN , P2P , K8S , Docker , TCP/IP , 协程 , DPDK , ffmpeg等) , 免费分享




推荐阅读