[英]is it graceful to use kill to exit the idle thread in thread poll?
退出空閑線程的實現如下:
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);
負責殺死空閑線程。 我的問題是殺死線程以使空閑線程退出是否很合適? 有沒有更好的方法呢?
不優雅,不。 如果在線程持有互斥鎖的同時殺死線程,則該互斥鎖將永遠不會被解鎖(除非您使用健壯的互斥鎖),因此至少應發送帶有當前線程鎖定的互斥鎖的kill,這樣您才能知道該線程已被殺死沒有它。 根據被殺死的線程的不同,這可能仍然不安全。
如果空閑線程正在等待條件變量,為什么不能僅使用條件變量來發信號通知它,使其醒來?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.