C++ - pthread not executing

C++ - pthread not executing

本文关键字:executing not pthread C++      更新时间:2023-10-16

我正在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()函数的助手函数,我正在使用它调用我的parceRequest函数。

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,那么一切都很好,但当我使用线程调用这个函数时,它被阻塞了。建议

查看您的代码:

static void * Parse::parseRequest_helper(void *c)    
{
cout<<"Inside Helper"; // Not coming here
return ((Parse *)c)->parseRequest(c);
}

只有当传递给此函数的void *参数是指向Parse的指针时,这才有意义。

void * Parse::parseRequest(void *info)
{
cout<<"Inside Parse Request";     //Not coming here
clientInfo *cInfo = (struct clientInfo *)info;
cout<<cInfo->ip;
}

只有当传递给该函数的info参数是指向clientInfo的指针时,这才有意义。

由于它是同一个参数,因此此代码没有任何意义。它可以是指向ParseclientInfo的指针,但不能两者都是。

cout<<"Inside Helper"; // Not coming here

你认为你没有达到那一行代码的结论是错误的。你是。因为没有endl,所以缓冲区不会被刷新,所以您无法判断。

您的代码没有向我们显示您的情况的详细信息,但从您的评论中,我对此有一些看法:

在你说// after this while loop is terminating的行中,你的生产代码和这里一样,还是你真的在它之后终止了你的块??记住,当你调用p.parseRequest(info)时,你正在调用线程中执行操作,所以在你解析的行完成后,但如果你使用线程,在行(pthread_create(...))之后,指定的线程可能没有事件启动,线程由操作系统安排在以后运行,你不应该认为解析是在它之后完成的。

// this is not reachable行中,您认为该行不应该执行吗?或者这是代码在运行时的行为?在任何情况下,pthread_create都会立即返回,稍后在另一个执行线程中运行作业,所以在代码中,您几乎会立即调用sleep(0),然后到达指定的行!!

sleep(0)的目的是让线程启动还是完成??在任何情况下,操作系统都会根据内部算法调度线程,因此在sleep(0)之后,线程执行可能仍处于挂起状态!!如果你想确保你的线程被启动/停止,你必须在你的线程和主线程之间使用同步机制(例如互斥)