【问题标题】:cancelling or killing a pthread取消或杀死一个 pthread
【发布时间】:2013-11-22 04:34:44
【问题描述】:
gcc (GCC) 4.6.3
valgrind-3.6.1

我创建了一个应用程序,它在 2 个不同的线程中发送和接收一些消息,用于发送和接收。对锁使用 pthread、条件变量和互斥锁。

但是,发送者会发送消息,然后通知接收者接收并处理它。它在一个while循环中执行此操作。

但是,如果我想通过使用 ctrl-c 并处理中断来退出应用程序,则会出现问题。如果没有消息被发送,那么接收者就会陷入等待接收的 while 循环中。

主线程将调用join并阻塞等待接收者完成。但它不像它在等待pthread_cond_wait

我正在考虑使用pthread_cancelpthread_kill。但我不喜欢这样做,因为它不允许线程正常退出。

非常感谢您的任何建议。

主要功能

    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;
}

发件人线程

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);
}

接收线程

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);
}

【问题讨论】:

  • 如果你不加入recv线程,它不会阻塞你的主线程的退出并且操作系统会停止两者。如果recv线程没有进程间资源等,就让OS停止吧。

标签: c multithreading pthreads


【解决方案1】:

你基本上有3个选择:

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

  2. 使用pthread_kill向线程发送信号。这不会“杀死”线程,它只是发送一个信号。在这种情况下,您必须在该线程中为您使用的信号注册了一个信号处理程序,并且该信号处理程序必须做一些事情来告诉线程退出。这并不比第三个选项特别好,因为信号处理程序仍然需要做一些事情来使pthread_cond_wait 循环退出。

  3. 为您的线程添加一个手动中断功能,该功能知道设置标志并向条件变量发出信号。然后围绕pthread_cond_wait 的循环应该检查标志并在标志被设置时退出线程。

我会推荐 (1) 或 (3)。使用pthread_cancel 是最通用的,但需要在线程中仔细处理以确保有合适的pthread_cleanup_push 调用来清理线程分配的所有资源、解锁所有互斥锁等等。编写手动中断功能可能需要更多工作,但可以最轻松地针对您的应用程序进行定制。

【讨论】:

  • 4.不需要时停止使用join。
猜你喜欢
  • 2012-08-15
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2019-08-24
  • 1970-01-01
相关资源
最近更新 更多