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