2013-11-27 27 views
0

所以很奇怪的问题。我在这里产生了我的线程。这应该保持循环,直到我杀死它。线程没有完成(尽管我打电话给pthread_join)

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

,功能并行线程运行:

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. 我的线程被正确终止了吗?

+0

“线程”应该退出而不是“返回”值。请将你的'return NULL'改为'pthread_exit()',你的代码应该可以正常工作。 – Ganesh

+2

@Ganesh调用返回是完全有效的。 'return foo;'相当于'pthread_exit(foo);'_unless_所讨论的线程是主线程。 –

回答

3

你的最后一行不打印,因为stdout是行缓冲和你没有在这最后printf()换行符(\n)。 exit()可能会冲洗stdout缓冲区。

+2

尽管我在猜测你可能需要在'printf()'中换行,我还会在'printf()'和'return'之间放一个'fflush(stdout)'以确保它的冲刷缓冲区。每次按照惯例都有一个换行符时,stdout会被刷新,但我不确定是否有任何标准需要它。换句话说,我认为当有一个换行符时,操作系统不会刷新缓冲区是合法的;它恰好是人们最常用的东西。 –

相关问题