【问题标题】:Thread not finishing (even though I'm calling pthread_join)线程未完成(即使我正在调用 pthread_join)
【发布时间】:2013-12-12 10:22:07
【问题描述】:

好奇怪的问题。我在这里产生我的线程。这应该一直循环,直到我杀死它。

void accept_connections(int sock_fd)
{
    while(1)
    {
            /*Whole bunch of irrelevant stuff*/
        pthread_create(&(new_connect->thread), NULL, &thread_dispatch, new_connect);
        printf("Thread spawned.\n");
        pthread_join(new_connect->thread, NULL);
            /*Exit when catches a sigint */
    }
}

以及 pthread 运行的函数:

void* thread_dispatch(void* new_connect)
{

    printf("Thread working.\n");

    http_t *http = malloc(sizeof(http_t));

    int bytes_read = http_read(http, fd);

    printf("read %d\n",bytes_read); //this prints
    printf("status %s\n",http->status); //this prints
    printf("body %s\n",http->body); //this prints
    const char* get_status = http_get_status(http);
    char* filename = process_http_header_request(get_status);
    printf("filename: %s", filename); //this doesn't print unless I do exit(1) on next line
    return NULL;
}
  1. 为什么最后一条语句没有打印出来?我正在调用 pthread_join ,它应该等待线程返回,然后终止,对吗?

  2. 我的线程是否以这种方式正确终止?

【问题讨论】:

  • 应该退出 thread 而不是 return 值。请将您的 return NULL 更改为 pthread_exit(),您的代码应该可以正常工作。
  • @Ganesh 调用 return 是完全有效的。 return foo; 等价于 pthread_exit(foo); 除非有问题的线程是主线程。

标签: c multithreading


【解决方案1】:

您的最后一行没有打印,因为 stdout 是行缓冲的,并且最后一行 printf() 中没有换行符 (\n)。 exit() 可能正在刷新stdout 缓冲区。

【讨论】:

  • 尽管我猜你可能想要在 printf() 中添加一个换行符,但我也会在 printf()return 之间添加一个 fflush(stdout); 以确保它刷新缓冲。按照惯例,每次有换行符时都会刷新标准输出,但我不确定是否有任何标准需要它。换句话说,我认为操作系统 not 在有换行符时刷新缓冲区是合法的;只是碰巧人们最常使用的那些。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多