在线程轮询中使用kill来退出空闲线程是否优雅?

时间:2014-03-14 08:34:54

标签: multithreading pthreads

退出空闲线程的实现如下:

int tp_delete_thread(TpThreadPool *pTp) {
    unsigned idx;
    TpThreadInfo *pThi;
    TpThreadInfo tT;

    //current thread num can't < min thread num
    if (pTp->cur_th_num <= pTp->min_th_num)
        return -1;
    //all threads are busy
    pThi = (TpThreadInfo *) ts_queue_deq_data(pTp->idle_q);
    if(!pThi)
        return -1;

    //after deleting idle thread, current thread num -1
    pthread_mutex_lock(&pTp->tp_lock);
    pTp->cur_th_num--;
    /** swap this thread to the end, and free it! **/
    memcpy(&tT, pThi, sizeof(TpThreadInfo));
    memcpy(pThi, pTp->thread_info + pTp->cur_th_num, sizeof(TpThreadInfo));
    memcpy(pTp->thread_info + pTp->cur_th_num, &tT, sizeof(TpThreadInfo));
    pthread_mutex_unlock(&pTp->tp_lock);

    //kill the idle thread and free info struct
    kill((pid_t)tT.thread_id, SIGKILL);
    pthread_mutex_destroy(&tT.thread_lock);
    pthread_cond_destroy(&tT.thread_cond);

    return 0;
}

对于活动线程,我们可以为线程设置一个标志,当线程完成作业时,它可以优雅地退出自己。

但是,空闲线程通常睡在pthread_cond_t上以获取作业,因此我们无法使其退出,因为活动线程会这样做。在上面的代码中,行kill((pid_t)tT.thread_id, SIGKILL);完成了杀死空闲线程的工作。我的问题是杀死线程以使空闲线程退出是优雅的吗?有没有更好的方法呢?

1 个答案:

答案 0 :(得分:1)

不优雅,不。如果你在持有互斥锁的情况下终止该线程,那么该互斥锁永远不会被解锁(除非你使用强大的互斥锁),所以你至少应该使用当前线程锁定的互斥锁发送kill,这样你就知道该线程被杀死了没有它。根据被杀死的线程确实可能不安全。

如果空闲线程正在等待条件变量,为什么不能使用条件变量发出信号,以便它被唤醒?