You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 17.10 VDS环境下验证单进程最大线程数限制

Got it,你遇到的pthread_create(): Resource temporarily unavailable确实是单进程线程资源耗尽的典型报错,刚好可以通过一个简单的C脚本直接验证单进程的最大线程数上限,下面是完整的方案:

验证单进程最大线程数的完整方案

1. 编写线程创建测试脚本

直接用C语言写一个循环创建线程的程序,它能直接调用pthread库,结果最准确。创建thread_test.c文件,内容如下:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

// 线程空函数,保持线程存活不退出
void *thread_func(void *arg) {
    while(1) {
        sleep(3600); // 让线程休眠,不占用CPU资源
    }
    return NULL;
}

int main() {
    pthread_t thread_id;
    int thread_count = 0;
    int create_result;

    printf("开始创建线程,直到资源耗尽...\n");
    while(1) {
        create_result = pthread_create(&thread_id, NULL, thread_func, NULL);
        if (create_result != 0) {
            printf("创建第%d个线程失败!错误信息:%s\n", thread_count + 1, strerror(create_result));
            break;
        }
        // 分离线程,避免主线程退出后产生内存泄漏
        pthread_detach(thread_id);
        thread_count++;
        // 每创建100个线程打印一次进度
        if (thread_count % 100 == 0) {
            printf("已成功创建 %d 个线程\n", thread_count);
        }
    }
    printf("当前单进程可创建的最大线程数为:%d\n", thread_count);
    // 保持主线程存活,方便你用ps命令实时验证线程数
    sleep(3600);
    return 0;
}

2. 编译并运行脚本

在Ubuntu 17.10服务器上执行以下命令:

  • 编译(如果没有gcc,先执行sudo apt install gcc libc6-dev安装依赖):
    gcc thread_test.c -o thread_test -lpthread
    
  • 运行测试程序:
    ./thread_test
    

3. 解读结果

程序会持续创建线程,直到触发Resource temporarily unavailable错误,此时输出的当前单进程可创建的最大线程数就是你要验证的上限值。

你可以打开另一个终端,用ps -Lf <进程PID>(把<进程PID>换成测试程序的PID)实时查看该进程的线程数,确认和程序输出的数值一致。

4. 额外检查相关系统限制

除了VDS虚拟化层面的限制,系统本身的参数也会影响单进程线程数:

  • 检查用户级总进程/线程限制:ulimit -u(单进程线程数不能超过这个值)
  • 检查线程默认栈大小:ulimit -s(栈越大,单进程能创建的线程越少,因为每个线程需要独立的栈空间)
  • 检查系统级最大线程数:sysctl kernel.threads-max
  • 检查内存映射限制:sysctl vm.max_map_count

如果你的VDS内存较小,栈大小也会间接限制线程数(比如5000个线程×8MB默认栈=40GB内存,内存不足也会触发资源错误),但结合你3proxy的表现,大概率是虚拟化层面做了单进程线程数上限限制。

内容的提问来源于stack exchange,提问作者Vladyslav Matviienko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:33:37