Pthread信号量TCP

时间:2017-02-18 23:19:16

标签: pthreads semaphore

我想在客户端创建2个线程,每个线程都会向服务器发送一条消息,并使用TCP protocole从服务器获取反弹或下载文件。当我没有添加pthread时,这个程序运行得很好。在客户端创建2个线程后,它不与服务器通信。通常,线程会告诉服务器它想要哪个操作,然后服务器响应,但是当一个线程发送消息时,服务器没有响应,并且该线程立即退出,下一个线程占用信号量但是退出而没有选择操作。

代码

void semaphore()
{
 int nThread = 2;
 int nSemaphore = 1;
 int nRet = -1;
 pthread_t threadIDs[nThread];
 nRet = sem_init(&sem, 0, nSemaphore);
 if(nRet == -1)
 {
     perror("Semaphore intialization failed!!!\n");
     exit(EXIT_FAILURE);
 }

 int i;
 for (i = 0; i < nThread; ++i)
 {
     nRet = pthread_create(&threadIDs[i], NULL, thread, NULL);
     if(nRet != 0)
     {
         perror("pthreas_create failed!!!\n");
         exit(EXIT_FAILURE);
     }
 }

 for(i = 0; i < nThread; ++i)
 {
     nRet = pthread_join(threadIDs[i], NULL);
     if(nRet != 0)
     {
         printf("Threan %d join failed!!!\n", i);
         exit(EXIT_FAILURE);
     }
 }

 sem_destroy(&sem);
}

在这里输入代码

void *thread(void* p)
{
 pthread_t id = pthread_self();
 sem_wait(&sem);
 pthread_mutex_lock(&mutex);

 int operation ;
 //向服务器(特定的IP和端口)发起请求
 struct sockaddr_in serv_addr;
 memset(&serv_addr, 0, sizeof(serv_addr));  //每个字节都用0填充
 serv_addr.sin_family = AF_INET;  //使用IPv4地址
 serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");  //具体的IP地址
 serv_addr.sin_port = htons(1234);  //端口

 printf("\nThis is client %ld", id);
 printf("\nWhich operation do you want:\n");
 printf("1:Sending message to server and get rebound\n");
 printf("2:Downlown a file from server\n");
 scanf("Your chose:%d", &operation);
 switch(operation)
 {
     case 1:
         {
             sendMessage(serv_addr);
             break;
         }

     case 2:
         {
             download(serv_addr);
             break;
         }

     default:
         break;
 }

 sem_post(&sem);
 pthread_mutex_unlock(&mutex);
}

从终端

This is client 139671599236864
Which operation do you want:
1:Sending message to server and get rebound
2:Downlown a file from server
Your choise:1

This is client 139671590844160
Which operation do you want:
1:Sending message to server and get rebound
2:Downlown a file from server

有人能告诉我问题在哪里吗?

0 个答案:

没有答案