退出空闲线程的实现如下:
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);行完成了杀死空闲线程的工作。我的问题是,杀死线程以使空闲线程退出是否得体?有没有更好的方法呢?
发布于 2014-03-14 16:45:43
它不优雅,不。如果您在线程持有互斥锁的同时终止线程,那么该互斥锁将永远不会被解锁(除非您使用健壮的互斥锁),因此您至少应该使用当前线程锁定的互斥锁发送终止,这样您就知道被终止的线程没有互斥锁。这仍然可能是不安全的,这取决于被杀死的线程所做的事情。
https://stackoverflow.com/questions/22399801
复制相似问题