0
退出的实施空闲线程如下:使用kill退出线程轮询中的空闲线程是否优雅?
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);
执行杀死空闲线程的工作。我的问题是优雅地杀死线程,使空闲线程退出?有没有更好的方法来做到这一点?
终止一个线程几乎是不安全的,除非线程是微不足道的。如果在线程内的任何一点都使用堆,那么泄漏最终会发生并最终发生。或者更糟的是,如果线程中有任何同步,则可能会导致锁定泄漏和死锁。您不能安全地停止不合作的线程,而只能停止整个进程。线程必须从内部结束。 – VoidStar
如果它是空闲的,为什么你不能将它排成一个告诉它退出的工作? –
什么是'thread_id',它是如何初始化的? – alk