线程未完成(即使我正在调用pthread_join)

时间:2013-11-27 01:20:30

标签: c multithreading

这么奇怪的问题。我在这里生成我的线程。这应该保持循环直到我杀了它。

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 */
    }
}

pthreads运行的函数:

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. 我的线程是否以这种方式正确终止?

1 个答案:

答案 0 :(得分:3)

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