2014-10-28 110 views
0

我認爲pthread_join應該總是返回一個值,然後允許主線程在此之後處理代碼。在我過去的經驗中,這將起作用。但現在我堅持下去了。不知何故,它只是不返回並阻止主線程。或者它可能是執行任務的主線程。我不知道爲什麼。在下面的代碼中,我直到終止客戶端才能到達「Thread created2」。任何想法?爲什麼pthread_join不能返回?

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); 
} 
+1

什麼是'runService'在做什麼?無論它在做什麼,它可能不會返回,主線程無法繼續,直到它完成。 – tangrs 2014-10-28 05:42:34

+1

也許你應該開始考慮接受來自努力幫助你的人的答案...... – Iuliu 2014-10-28 10:17:12

回答

4

從我們可以看到通過 線程 規定來終止線程下列有關pthread_join

將在pthread_join()函數等待的文檔。如果該線程已經終止,則 pthread_join()立即返回。線程 指定的線程必須可以連接。

這表明你的情況父線程正在等待其子線程PT完成。正在執行runService的子線程仍未返回/完成。因此,你的父線程將繼續等待完成(而不是從pthread_join方法返回)。

您應該嘗試查看runService的代碼以瞭解這種情況。

相關問題