netdata:获取系统最多能够创建多少线程数

1060 篇文章 300 订阅

shell

$ cat /proc/sys/kernel/pid_max    #查看系统支持的最大线程数
131072

c代码

#include <stdio.h>
#include <fcntl.h>
#include <zconf.h>

#define likely(x)  __builtin_expect((x), 1)
#define unlikely(x)  __builtin_expect((x), 0)
static inline int read_single_number_file(const char *filename, unsigned long long *result);
static inline int read_file(const char *filename, char *buffer, size_t size);
static inline unsigned long long str2ull(const char *s);

pid_t pid_max = 32768;
pid_t get_system_pid_max(void) {
    static char read = 0;
    if(read) return pid_max;
    read = 1;

    char filename[FILENAME_MAX + 1];
    snprintf(filename, FILENAME_MAX, "/proc/sys/kernel/pid_max");

    unsigned long long max = 0;
    if(read_single_number_file(filename, &max) != 0) {
        printf("Cannot open file '%s'. Assuming system supports %d pids.", filename, pid_max);
        return pid_max;
    }

    if(!max) {
        printf("Cannot parse file '%s'. Assuming system supports %d pids.", filename, pid_max);
        return pid_max;
    }

    pid_max = (pid_t) max;
    return pid_max;
}

int main() {
    get_system_pid_max();

    printf("pid_max = %d", pid_max);

    return 0;
}


static inline int read_single_number_file(const char *filename, unsigned long long *result) {
    char buffer[30 + 1];

    int ret = read_file(filename, buffer, 30);
    if(unlikely(ret)) {
        *result = 0;
        return ret;
    }

    buffer[30] = '\0';
    *result = str2ull(buffer);
    return 0;
}

static inline int read_file(const char *filename, char *buffer, size_t size) {
    if(unlikely(!size)) return 3;

    int fd = open(filename, O_RDONLY, 0666);
    if(unlikely(fd == -1)) {
        buffer[0] = '\0';
        return 1;
    }

    ssize_t r = read(fd, buffer, size);
    if(unlikely(r == -1)) {
        buffer[0] = '\0';
        close(fd);
        return 2;
    }
    buffer[r] = '\0';

    close(fd);
    return 0;
}
static inline unsigned long long str2ull(const char *s) {
    unsigned long long n = 0;
    char c;
    for(c = *s; c >= '0' && c <= '9' ; c = *(++s)) {
        n *= 10;
        n += c - '0';
    }
    return n;
}

在这里插入图片描述

测试系统最多能够创建多少线程数

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

void *foo(void *arg)
{
    return((void *)0);
}
int main()
{
    int i = 0;
    pthread_t thread;

    while (1) {
        if (pthread_create(&thread, NULL, foo, NULL) != 0){
            printf("%s", strerror(errno));
            return 0;
        }

        i ++;
        printf("i = %d\n", i);
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值