使用pthread_detach()时为什么线程不能并发工作?

时间:2015-05-09 14:54:52

标签: c multithreading pthreads concurrent-programming

我编写了服务器客户端代码,其中服务器通过线程并发。我的代码包含:

    //main code here
    for(; ;)                                   
    {
            printf("---------SERVER WAITING FOR CLIENT------------\n");
            len = sizeof(client_addr);
            connfd = accept(sd,(struct sockaddr *)&client_addr,&len);       //server waiting for client
            if (0 > connfd)                         //error handling for accept
            {
                    perror("CONNECTION ERROR:");
                    exit(EXIT_FAILURE);
            }
            memset(addr, 0, BUFFER_SIZE);           //initializing address to NULL
            printf("Connection from %s \n", inet_ntop(AF_INET, &client_addr.sin_addr, addr, sizeof(addr)));

            arg->sd = connfd; /*copy socket to structure */
            ret = pthread_create(&ntid, NULL, thread_fun,(void *)arg);       //calling thread function
            if (0 > ret)
            {
                    printf("error on thread creation\n");
                    close(connfd);
            }
            pthread_detach(ntid);
            printf("client server successfully\n");
            close(connfd);
  }


 void * thread_fun (void * argument)
 {
    struct ThreadArg *thArg = (struct ThreadArg *)argument;/*cast into structure parameter*/
    int chance = 0;
    int flag = 0,ret = 0;
    char *token[4];
    int position = 0;
    char *user_buffer = NULL;
    printf("thread function started\n");
    //code to run other function like reading and writing
    user_buffer = receive_user_details(thArg->sd);/*receive the  details from user*/
     //codes to call different functions
     //..............
    close(thArg->sd);
    pthread_exit(NULL);

  }

但是我的代码已经运行但是在服务器上了

---------SERVER WAITING FOR CLIENT------------
Connection from 10.253.222.55
client server successfully
---------SERVER WAITING FOR CLIENT------------
the total size received:21
Read:: Bad file descriptor
the value from client :(null)
receiving user data failed

为什么此功能最初打印“客户端服务器成功”?为什么第一个线程最初结束?是代码(线程)上的任何问题?如何在c?

中编写代码来获取并发服务器的输出

0 个答案:

没有答案