c++ - Linux 内核 2.4.20 和 2.4.36 中的 pthread_create 差异

标签 c++ linux pthreads

我在运行 kernel 2.4.20kernel 2.4.38 的两个系统上有一些代码。 它们都有 gcc 3.2.2glibc 2.3.2

kernel 2.4.38 下,pthread_t 句柄不会被重用。在重负载测试下,一旦句柄达到 0xFFFFFFFF,应用程序就会崩溃。

(我首先怀疑这是因为应用程序在 IT 使用网络端口扫描器的部署中崩溃 - 创建线程是为了处理套接字连接)

这个简单的例子重现了这个问题:

void* ThreadProc(void* param)
{
    usleep(10000);
    printf(" Thread 0x%x\n", (unsigned int)pthread_self());
    usleep(10000);
    return NULL;
}

int main(int argc, char* argv[])
{
    pthread_t sThread;

    while(1)
    {
      pthread_create(&sThread, NULL, ThreadProc, NULL); 
      printf("Created 0x%x\n", (unsigned int)sThread);  
      pthread_join(sThread, NULL);
    };

    return 0;
}

在 2.4.20 下:

    Created 0x40838cc0
     Thread 0x40838cc0
    Created 0x40838cc0
     Thread 0x40838cc0
    Created 0x40838cc0
     Thread 0x40838cc0
...and on and on...

在 2.4.36 下:

    Created 0x4002
     Thread 0x4002
    Created 0x8002
     Thread 0x8002
    Created 0xc002
     Thread 0xc002
...keeps growing...

如何让 kernel 2.4.36 回收句柄?不幸的是我不能轻易改变内核。 谢谢!

最佳答案

如果您的观察是正确的,则只有两种可能的解决方案。

要么

  1. 升级内核。这对您来说可能可行,也可能不可行。
  2. 在您的应用程序中回收线程。

选项 2 是您可以执行的操作,即使内核运行不正常也是如此。您可以持有一个线程池,这些线程在不使用时保持休眠状态。线程池是一种广为人知的软件工程模式(参见 http://en.wikipedia.org/wiki/Thread_pool_pattern )。这可能是更适合您的解决方案。

关于c++ - Linux 内核 2.4.20 和 2.4.36 中的 pthread_create 差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11344393/

相关文章:

c++ - 内存分配器范围的设计

Linux(CENTOS 6)在数据库中存储/etc/shadow密码

c - pthread_rwlock_rdlock 导致读取器数量变为负数

c - pthreads 没有真正的加速

c++ - 如何将元素插入 multimap ?

程序中的 C++ 错误

c++ - 如何在 Mac 终端中查看 C++ 函数的名称

java - 使用 JNI 问题构建 .so 文件

linux - Linux 中的无缓冲 I/O

c - Linux 上的简单 pthreads 和信号程序不会运行