Linux的多任务编程(3)

当线程池退出后,需要释放所用的资源,包括以下五个步骤:

设置线程退出标记;

禁止添加新任务到任务链表;

设置线程池销毁标记;

等待所有已经建立的线程退出;

释放线程池所占的内存空间.

int tpool_destroy(tpool_t *pool, int finish)
{
    int i, rtn;
    tpool_work_t *cur;  /*当前工作线程*/
    lprintf(log, INFO, "destroy pool begin!\n");
    /* 释放对任务链表的独占 */
    if((rtn = pthread_mutex_lock(&(pool->queue_lock))) != 0) 
    {
        lprintf(log,FATAL,"pthread mutex lock failure\n");
        return -1;
    }
    /* 第一步,设置线程退出标记 */
    lprintf(log, INFO, "destroy pool begin 1!\n");
    if(pool->queue_closed || pool->shutdown)
    {
        if((rtn = pthread_mutex_unlock(&(pool->queue_lock))) != 0)
        {
            lprintf(log,FATAL,"pthread mutex lock failure\n");
            return -1;
        }
        return 0;
    }
    /* 第二步,禁止新任务加入任务链表 */
    lprintf(log, INFO, "destroy pool begin 2!\n");
    pool->queue_closed = 1;
    if(finish)
    {
        while(pool->cur_queue_size != 0)
        {
            if((rtn = pthread_cond_wait(&(pool->queue_empty),&(pool->queue_lock))) != 0)
            {
                lprintf(log,FATAL,"pthread_cond_wait %d\n",rtn);
                return -1;
            }
        }
    }
    /* 第三步,设置线程池销毁标记 */
    lprintf(log, INFO, "destroy pool begin 3!\n");
    pool->shutdown = 1;
    if((rtn = pthread_mutex_unlock(&(pool->queue_lock))) != 0)
    {
        lprintf(log,FATAL,"pthread mutex unlock failure\n");
        return -1;
    }
    /* 第四步,等待所有已建立的线程退出 */
    lprintf(log, INFO, "destroy pool begin 4!\n");
    if((rtn = pthread_cond_broadcast(&(pool->queue_not_empty))) != 0)
    {
        lprintf(log,FATAL,"pthread_cond_boradcast %d\n",rtn);
        return -1;
    }
    if((rtn = pthread_cond_broadcast(&(pool->queue_not_full)))  != 0)
    {
        lprintf(log,FATAL,"pthread_cond_boradcast %d\n",rtn);
        return -1;
    }
    for(i = 0; i < pool->num_threads; i++)
    {
        if((rtn = pthread_join(pool->threads[i],NULL)) != 0)
        {
            lprintf(log,FATAL,"pthread_join %d\n",rtn);
            return -1;
        }
    }
    /* 第五步,释放线程池所占的内存空间 */
    free(pool->threads);
    while(pool->queue_head != NULL)
    {
        cur = pool->queue_head->next;
        pool->queue_head = pool->queue_head->next;
        free(cur);
    }
    free(pool);
    lprintf(log, INFO, "destroy pool end!\n");
    return 0;
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/2171544ed330f750996edb69a5ca4e43.html