我在 C++ (linux) 中实现了一个多线程服务器。我的主要目标是使用线程调用函数将客户端详细信息发送到其他函数。这是我的代码片段:
while(true)
{
if((acceptId = accept(sockId,(struct sockaddr*)&clientAddr,(socklen_t *)&address)) == -1)
perror("Accept:");
inet_ntop(clientAddr.ss_family,get_ip_address((struct sockaddr *)&clientAddr),ip1, sizeof(ip1));
clientInfo *cInfo = new clientInfo;
cInfo->acceptId = acceptId;
strcpy(cInfo->ip, ip1);
void *info = cInfo;
pthread_t thread_request;
pthread_create(&thread_request,NULL,&Parse::parseRequest_helper,info); // after this while loop is terminating
//p.parseRequest(info);
sleep(0);
cout<<"\nserver: got connection from "<<ip1<<" Port:"<<clientport; // this is not reachable
}
// 这是我的 parseRequest() 函数的辅助函数,我正在调用我的 parseRequest 函数。
static void * Parse::parseRequest_helper(void *c)
{
cout<<"Inside Helper"; // Not coming here
return ((Parse *)c)->parseRequest(c);
}
void * Parse::parseRequest(void *info)
{
cout<<"Inside Parse Request"; //Not coming here
clientInfo *cInfo = (struct clientInfo *)info;
cout<<cInfo->ip;
}
如果我不使用线程并直接在 while 循环内调用 parseRequest,那么一切都很好,但是当我使用线程调用此函数时,它会阻塞。建议 ??