为什么创建的线程数小于最大线程数(thread-max)?

4

使用以下代码:

void yield_sleep(void)
{
    using namespace std::chrono;

    static size_t thread_num;

    auto start{high_resolution_clock::now()};
    std::this_thread::yield();
    auto end{high_resolution_clock::now()};

    std::cout << thread_num++
              << "|Waiting for: "
              << duration_cast<microseconds>(end - start).count()
              << " ms."
              << std::endl;
}

int main(void)
{
    std::vector<std::thread> tp(62434);

    std::generate(tp.begin(), tp.end(), []() { return std::thread(yield_sleep); });
    std::for_each(tp.begin(), tp.end(), [](auto& t) { t.join(); });
}

该程序创建了32718个线程并抛出了一个异常:
terminate called after throwing an instance of 'std::system_error'
  what():  Resource temporarily unavailable

但是在/proc/sys/kernel/threads-max中,该值为62434。问题出在哪里?为什么我的程序在创建线程时抛出异常?


threads-max 值代表的是每个进程的限制还是系统范围内的限制? - 1201ProgramAlarm
@1201ProgramAlarm,根据这个thread-max值是系统范围内的限制。 - Ghasem Ramezani
@RobertoCaboni,每次运行都不一样。 - Ghasem Ramezani
4
相关/可能重复:理解pid_max、ulimit -u和thread_max之间的区别该文章讨论了在Linux系统中限制进程(process)数量的三种方式:pid_max、ulimit -u和thread_max。pid_max是内核参数,用于限制系统中可以分配的最大PID数量;ulimit -u是用户级别的限制,它限制了单个用户在其会话期间启动的进程数量;而thread_max限制每个进程可以拥有的线程数。这些限制对系统管理员很重要,因为过多的进程或线程可能导致系统资源耗尽并降低系统性能。 - François Andrieux
系统可能会阻止“fork bomb”的原因有很多。 - Mike Robinson
显示剩余3条评论
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接