【发布时间】: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;
}
为什么最后一条语句没有打印出来?我正在调用 pthread_join ,它应该等待线程返回,然后终止,对吗?
我的线程是否以这种方式正确终止?
【问题讨论】:
-
应该退出
thread而不是return值。请将您的return NULL更改为pthread_exit(),您的代码应该可以正常工作。 -
@Ganesh 调用 return 是完全有效的。
return foo;等价于pthread_exit(foo);除非有问题的线程是主线程。
标签: c multithreading