我的一个 friend 正在尝试用 C++ 修复一个为 Windows 编写的自定义 http 服务器,以便在 Linux 中运行。我试图帮助他,但我发现的一切似乎都太明显了。
应用程序会在每次收到请求时创建一个线程。该线程处理请求并结束。在一定数量的请求(超过 300 个)之后,不再创建新线程。
我发现的是可以创建的线程是有限制的。但看起来完成的线程仍然存在。这是代码的问题还是线程处理程序永远不会被释放?
这是我的 friend 从应用程序中提取的一些代码:
pthread_t threadID;
StartingArgs *arg = new StartingArgs( &(this->cameraCounts), mapToSend,&(this->mapMutex), &(this->mutex), this->config );
if( pthread_create(&threadID, NULL, (this->startingRoutine) , (void*)arg ) != 0 )
{
ConsoleMessages::printDate();
cout<< "snapshot maker: new thread creation failed\n";
}
void *CameraCounter::startingRoutine( void *arg )
{
//stuff to do. removed for debugging
delete realArgs;
return NULL;
}
最佳答案
看起来你有一堆“可连接”的线程。他们正在等待有人对他们调用 pthread_join() 。如果您不想这样做(例如,为了获取线程的返回值),您可以将线程创建为“分离的”:
pthread_t threadID;
pthread_attr_t attrib;
pthread_attr_init(&attrib);
pthread_attr_setdetachstate(pthread_attr_t &attrib, PTHREAD_CREATE_DETACHED);
StartingArgs *arg = new StartingArgs( &(this->cameraCounts), mapToSend,&(this->mapMutex), &(this->mutex), this->config );
if( pthread_create(&threadID, &attrib, (this->startingRoutine) , (void*)arg ) != 0 )
{
ConsoleMessages::printDate();
cout<< "snapshot maker: new thread creation failed\n";
}
pthread_attr_destroy(&attrib);
void *CameraCounter::startingRoutine( void *arg )
{
//stuff to do. removed for debugging
delete realArgs;
return NULL;
}
关于c++ - Linux C++ 线程已死,但 "hanging"- 线程限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4001370/