首页 文章

取消或杀死pthread

提问于
浏览
2
gcc (GCC) 4.6.3
valgrind-3.6.1

我创建了一个应用程序,在2个不同的线程中发送和接收一些消息,用于发送和接收 . 使用pthreads,条件可变和锁定互斥锁 .

但是,发送方将发送消息,然后通知接收方接收消息并进行处理 . 它在while循环中执行此操作 .

但是,如果我想通过使用ctrl-c并处理中断来退出应用程序,则会出现问题 . 如果没有发送消息,则接收器卡在等待接收的while循环中 .

主线程将调用join和block等待接收器完成 . 但它没有等待 pthread_cond_wait .

我在考虑使用 pthread_cancelpthread_kill . 但我不允许线程正常退出 .

非常感谢任何建议 .

main function

void main(void)
    {
        /* Do some stuff here */

    /* Start thread that will send a message */
    if(pthread_create(&thread_recv_id, &thread_attr, thread_recv_fd, NULL) == -1) {
        fprintf(stderr, "Failed to create thread, reason [ %s ]",
            strerror(errno));
            break;
        }
        printf("Start listening for receiving data'\n");

        /* Start thread to receive messages */
        if(pthread_create(&thread_send_id, &thread_attr, thread_send_fd, NULL) == -1) {
            fprintf(stderr, "Failed to create thread for receiving, reason [ %s ]",
                    strerror(errno));
            break;
        }

    /* Clean up threading properties */
    pthread_join(thread_send_id, NULL);
    pthread_join(thread_recv_id, NULL); <---- blocking here waiting for the recv thread to finish

    pthread_mutex_destroy(&mutex_queue);
    pthread_cond_destroy(&cond_queue);

    return 0;
}

sender thread

void *thread_send_fd()
{
        pthread_mutex_lock(&mutex_queue);
        if(send_fd((int)fd) == FALSE) {
            /* Just continue to send another item */
            continue;
        }
        /* Signal the waiting thread to remove the item that has been sent */
        pthread_cond_signal(&cond_queue);

        pthread_mutex_unlock(&mutex_queue);
}

receiver thread

void *thread_recv_fd()
{
    while(is_receiving()) {
        pthread_mutex_lock(&mutex_queue);

        /* Wait for an item to be sent on the queue */
        pthread_cond_wait(&cond_queue, &mutex_queue); <---- waiting here

        queue_remove();
        pthread_mutex_unlock(&mutex_queue);
    }

    pthread_exit(NULL);
}

1 回答

  • 9

    你基本上有3个选择:

    • 使用 pthread_cancel . 这将中断 pthread_cond_wait 调用,然后退出线程,调用在 pthread_cleanup_push 注册的取消处理程序 .

    • 使用 pthread_killsend a signal to the thread . 这并不比第三个选项好,因为信号处理程序仍然需要做一些事情来使 pthread_cond_wait 循环退出 .

    • 为线程添加手动中断功能,该线程知道设置标志并发出条件变量信号 . 然后,如果设置了标志,那么 pthread_cond_wait 周围的循环应检查该标志并退出该线程 .

    我建议(1)或(3) . 使用 pthread_cancel 是最通用的,但需要在线程中小心处理,以确保有合适的 pthread_cleanup_push 调用来清理线程分配的所有资源,解锁所有互斥锁等等 . 编写手动中断功能可能会带来更多工作,但最容易为您的应用程序量身定制 .

相关问题