gpt4 book ai didi

c - 为什么 pthread_join 没有返回?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:58:01 26 4
gpt4 key购买 nike

我认为 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);
}

最佳答案

从文档中我们可以阅读以下关于 pthread_join 的信息

The pthread_join() function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join() returns immediately. The thread specified by thread must be joinable.

这表明在您的情况下,父线程正在等待其子线程pt 完成。正在执行 runService 的子线程 pt 仍未返回/完成。因此,您的父线程将继续等待完成(不从 pthread_join 方法返回)。

您应该尝试查看runService 的代码以了解这种情况。

关于c - 为什么 pthread_join 没有返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26601525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com