Raspberry PI多线程套接字问题C.

时间:2016-07-05 16:05:00

标签: c multithreading sockets raspberry-pi

所以我有一个非常基本的tcp服务器,它有两个线程监听两个独立的端口。但是,当代码运行时,永远不会创建第二个线程,并且看起来第一个线程实际上阻止整个程序创建下一个线程。这是代码......(非常简单)

void *Listener1();
void *Listener2();

int main()
{
    pthread_t thread1, thread2;
    pthread_create(&thread1, NULL,Listener1(), NULL);
    pthread_create(&thread2, NULL,Listener2(), NULL);
    sleep(50);
    return 0;
}
void *Listener1()
{
     int sockfd, newsockfd;
     socklen_t clilen;
     struct sockaddr_in serv_addr, cli_addr;

     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
        puts("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(12346);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0) 
              puts("ERROR on binding");
     listen(sockfd,1);
     clilen = sizeof(cli_addr);

     newsockfd = accept(sockfd, 
                 (struct sockaddr *) &cli_addr, 
                 &clilen);
     if (newsockfd < 0) 
          puts("ERROR on accept");
     else
        puts("Client connected!");

     close(newsockfd);
     close(sockfd);
     return 0; 
}
void *Listener2()
{
    puts("hi)");
     int sockfd, newsockfd;
     socklen_t clilen;
     struct sockaddr_in serv_addr, cli_addr;

     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0) 
        puts("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(12345);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0) 
              puts("ERROR on binding");
     listen(sockfd,1);
     clilen = sizeof(cli_addr);
     newsockfd = accept(sockfd, 
                 (struct sockaddr *) &cli_addr, 
                 &clilen);
     if (newsockfd < 0) 
          puts("ERROR on accept");
     else
        puts("Client connected!");

     close(newsockfd);
     close(sockfd);
     return 0; 
}

1 个答案:

答案 0 :(得分:3)

仔细看看

pthread_create(&thread1, NULL,Listener1(), NULL);
//                                     ^^
//                           causes the function to be called

这里你没有传递指向Listener1函数的指针,你实际上是调用它,它的返回值将被用作线程函数的函数指针,如果它回来了。

您应该将指针传递给函数:

pthread_create(&thread1, NULL,&Listener1, NULL);