Kol*_* H. 0 c sockets linux multithreading pthreads
我认为 pthread_join 应该总是返回一个值,然后允许主线程在此之后处理代码。根据我过去的经验,这会奏效。但现在我被它困住了。不知何故,它只是不返回并阻塞主线程。或者它可能是执行任务的主线程。我不知道为什么。在下面的代码中,在终止客户端之前,我无法访问“Thread created2”。任何的想法?
int main(int argc, char *argv[]) {
int sockfd, port; /* listen on sock_fd, new connection on new_fd */
struct sockaddr_in my_addr; /* my address information */
struct sockaddr_in their_addr; /* connector's address information */
socklen_t sin_size;
if(signal(SIGINT, sigintEvent) == SIG_ERR)
printf("can't catch SIGINT!");
/* generate the socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
if (argc > 1) {
port = atoi(argv[1]);
} else {
port = MYPORT;
}
/* generate the end point */
my_addr.sin_family = AF_INET; /* host byte order */
my_addr.sin_port = htons(port); /* short, network byte order */
my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
/* bzero(&(my_addr.sin_zero), 8); ZJL*/ /* zero the rest of the struct */
/* bind the socket to the end point */
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) \
== -1) {
perror("bind");
exit(1);
}
/* start listnening */
if (listen(sockfd, MAXCONNECTIONS) == -1) {
perror("listen");
exit(1);
}
createPool(MAXCONNECTIONS);
/* create a node pointer as head of the list */
head = (node*)malloc(sizeof(node));
openFile();
printf("server starts listnening ...\n");
int new_fd;
sin_size = sizeof(struct sockaddr_in);
while((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size))) {
printf("Accepted!\n");
printf("server: got connection!\n");
//tNode* tThread = (tNode*)threadDequeue();
pthread_t pt;
printf("Got tThread.\n");
if((pthread_create(&pt, NULL, runService,(void*)&new_fd)) != 0) {
printf("error creating thread.");
abort();
}
printf("Thread created.\n");
if( pthread_join(pt, NULL) != 0 ) {
printf("error joining thread");
abort();
}
printf("Thread created2.\n");
}
exit(1);
}
Run Code Online (Sandbox Code Playgroud)
从文档中我们可以阅读到以下关于pthread_join 的信息
pthread_join() 函数等待thread 指定的线程终止。如果该线程已经终止,则 pthread_join() 立即返回。thread 指定的线程必须是可连接的。
这表明在您的情况下,父线程正在等待其子线程pt的完成。正在执行的子线程ptrunService仍未返回/完成。因此,您的父线程将继续等待完成(不从 pthread_join 方法返回)。
您应该尝试查看代码runService以了解这种情况。
| 归档时间: |
|
| 查看次数: |
3100 次 |
| 最近记录: |