如果程序需要创建大量的线程,要考虑用 root 用户执行这个程序。

来源:互联网 发布:csgo网络连接失败 编辑:程序博客网 时间:2024/05/17 22:45

在Linux下,只有root用户才可以创建很多很多线程(这里说的就是线程,不是进程),普通用户创建线程的数量是有限制的,超过这个限制创建就会失败。


下面是个实例(test.c):


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

#define MAX_TEST_THREAD 3000

void * handle(void *data)
{
    while(1)
        sleep(1);
}

int main()
{
    int     i, n, r;
    pthread_t   pid;

    printf("Now try to create %d threads.\n",MAX_TEST_THREAD);

    for(i=0, n=0; i<MAX_TEST_THREAD; i++)
    {
        r = pthread_create(&pid,NULL,handle,NULL);
    if(r != 0)
    {
        fprintf(stderr,"pthread_create error: %s\n", strerror(r));
        break;
    }else
    {
        n++;
    }
    }

    printf("%d threads have been created!\n", n);

    sleep(5);

    exit(0);
}


用普通用户 oracle 执行:

[oracle@localhost]$ ./test
Now try to create 3000 threads.
pthread_create error: Resource temporarily unavailable
885 threads have been created!                 // oracle用户创建线程有限制,不能创建3000个线程。


切换到 root 用户执行:


[oracle@localhost]$ su
Password:
[root@localhost]# ./test
Now try to create 3000 threads.
3000 threads have been created!                 // root用户能创建3000个线程。
[root@localhost]#


所以,如果程序需要创建大量的线程,要考虑切换到 root 下执行这个程序。