![pids.current 低于 pids.max 但无法在 Ubuntu VPS 中创建线程](https://linux22.com/image/173177/pids.current%20%E4%BD%8E%E4%BA%8E%20pids.max%20%E4%BD%86%E6%97%A0%E6%B3%95%E5%9C%A8%20Ubuntu%20VPS%20%E4%B8%AD%E5%88%9B%E5%BB%BA%E7%BA%BF%E7%A8%8B.png)
问题 我有一个配备 Ubuntu 18.04 LTS、4vCore 和 8GB RAM 的 VPS。我不确切知道该 VPS 的最大 nprocs。
我做了什么/尝试过什么
我运行此命令sudo cat /sys/fs/cgroup/pids/pids.current
来查看当前进程,输出为 73。然后我运行此命令sudo cat /sys/fs/cgroup/pids/pids.max
,输出为 400。我假设我的 VPS 有超过 300 个线程需要创建。我已经运行这个 C 程序来测试我可以创建的许多线程:
/* compile with: gcc -pthread -o thread-limit thread-limit.c */
/* originally from: http://www.volano.com/linuxnotes.html */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#define MAX_THREADS 100000
#define PTHREAD_STACK_MIN 1*1024*1024*1024
int i;
void run(void) {
sleep(60 * 60);
}
int main(int argc, char *argv[]) {
int rc = 0;
pthread_t thread[MAX_THREADS];
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
pthread_attr_setstacksize(&thread_attr, PTHREAD_STACK_MIN);
printf("Creating threads ...\n");
for (i = 0; i < MAX_THREADS && rc == 0; i++) {
rc = pthread_create(&(thread[i]), &thread_attr, (void *) &run, NULL);
if (rc == 0) {
pthread_detach(thread[i]);
if ((i + 1) % 100 == 0)
printf("%i threads so far ...\n", i + 1);
}
else
{
printf("Failed with return code %i creating thread %i (%s).\n",
rc, i + 1, strerror(rc));
// can we allocate memory?
char *block = NULL;
block = malloc(65545);
if(block == NULL)
printf("Malloc failed too :( \n");
else
printf("Malloc worked, hmmm\n");
}
}
sleep(60*60); // ctrl+c to exit; makes it easier to see mem use
exit(0);
}
来源:线程限制.c
这是输出:
sebo@h2885222:~$ ./thread-limit
Creating threads ...
Failed with return code 11 creating thread 10 (Resource temporarily unavailable).
Malloc worked, hmmm
我只能再创建 10 个线程,这让我感到好奇。是否有任何限制将我的 VPS 设置为不超过该线程数?难道文件是pids.max
假的?
答案1
错误代码 11 如下所示EAGAIN
:
// /usr/include/asm-generic/errno-base.h
#define EAGAIN 11 /* Try again */
从man pthread_create
:
EAGAIN A system-imposed limit on the number of threads was encountered. There are a number of limits that may trigger this error: the RLIMIT_NPROC soft resource limit (set via setrlimit(2)), which limits the number of processes and threads for a real user ID, was reached; the kernel's system-wide limit on the number of processes and threads, /proc/sys/kernel/threads-max, was reached (see proc(5)); or the maximum number of PIDs, /proc/sys/ker‐ nel/pid_max, was reached (see proc(5)).
这可以让您了解自己遇到的限制。