当我限制它们的数量时,GNU/Linux 是否将进程和线程计数在一起?

Pet*_*ber 12 linux gnu process threads

我想用/etc/security/limits.confnproc 值限制我机器上每个用户的进程数。

我在这里读到Linux 不区分进程和线程?

我当前每个用户的 nproc 限制是 1024,但如果这也包括线程,那么在我看来它太低了。手册页limits.conf只提到了 nproc 的“进程”,没有其他任何内容。

// 使用 Boost 编辑 // C++ 示例代码 // g++ -o boost_thread boost_thread.cpp -lboost_thread

#include <unistd.h>
#include <iostream>
#include <boost/thread.hpp>
using namespace std;

int counter;

void print_thread(int i) {
    counter++;
    cout << "thread(" << i << ") counter " << counter << "\n";
    sleep(5);
    counter--;
}

int main() {
    int i = 0;
    int max = 1000000;

    while (i < max) {
        boost::thread(print_thread, i);
        i++;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

测试(删除了一些行):

$ ulimit -u
1024
$ ./thread 
...
...
...
thread(828) counter 828
thread(829) counter 829
thread(830) counter 830
thread(831) counter 831
thread(832) counter 832
thread(610) counter thread(833833) counter 834

thread(834) counter 835
thread(835) counter 836
thread(836) counter 837
thread(837) counter 838
thread(838) counter 839
thread(839) counter 840
thread(840) counter 841
thread(841) counter 842
thread(842) counter 843
thread(843) counter 844
thread(844) counter 845
thread(845) counter 846
thread(846) counter 847
thread(847) counter 848
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::thread_resource_error> >'
  what():  boost::thread_resource_error
Aborted (core dumped)
Run Code Online (Sandbox Code Playgroud)

我的笔记本电脑在闲置时使用了大约 130 个进程。因此,nproc或更广泛的Linux不会区分进程和线程。这对我来说似乎是合理的,因为线程也可能令人筋疲力尽,而不仅仅是进程。

Tot*_*tor 16

nproc您所谈论的限制适用于可运行实体,因此它限制了线程(因此也限制了包含它们的进程)。每个进程至少有一个线程(主线程),因此只能运行线程。严格来说,进程不是“可运行的”。

这个答案解释了 Linux 中线程和进程之间的真正区别。

我在daya的答案中测试了代码(也在sleep(1);线程代码中添加),与他不同(?!),当创建太多线程时,我达到了限制:pthread_create()正在返回EAGAIN。该pthread_create(3)文件说,有关此错误的情况如下:

EAGAIN

资源不足,无法创建另一个线程,或者遇到系统对线程数施加的限制。后一种情况可能以两种方式发生:达到 RLIMIT_NPROC 软资源限制(通过 setrlimit(2) 设置),它限制了真实用户 ID 的进程数;或者达到了内核对线程数的系统范围限制,/proc/sys/kernel/threads-max。

我在内核源代码中没有看到特定的每线程限制,我只在那里看到,这是您可以在(使用)或.RLIMIT_NPROClimits.confnproculimit -usetrlimit(2)