首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在线程轮询中使用kill退出空闲线程是否得体?

在线程轮询中使用kill退出空闲线程是否得体?
EN

Stack Overflow用户
提问于 2014-03-14 16:34:54
回答 1查看 85关注 0票数 0

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

代码语言:javascript
复制
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);行完成了杀死空闲线程的工作。我的问题是,杀死线程以使空闲线程退出是否得体?有没有更好的方法呢?

EN

回答 1

Stack Overflow用户

发布于 2014-03-14 16:45:43

它不优雅,不。如果您在线程持有互斥锁的同时终止线程,那么该互斥锁将永远不会被解锁(除非您使用健壮的互斥锁),因此您至少应该使用当前线程锁定的互斥锁发送终止,这样您就知道被终止的线程没有互斥锁。这仍然可能是不安全的,这取决于被杀死的线程所做的事情。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22399801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档