c++ - 为什么创建的线程数小于thread-max?

标签 c++ multithreading gcc gcc9

使用此代码:

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。有什么问题?为什么我的程序在创建线程期间抛出异常?

最佳答案

正如 @1201ProgramAlarm 所提到的和 @Francois Andrieux在评论中。 thread-max value 是系统范围的限制,为了创建更多线程,我们需要在内核设置中进行一些修改:

  • Understanding the difference between pid_max, ulimit -u and thread_max
  • Maximum number of threads per process in Linux?
  • 关于c++ - 为什么创建的线程数小于thread-max?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60849669/

    相关文章:

    c++ - 我必须更改我的数字的最后一位和第一位,但不能仅对整数或循环使用函数。例如从12345到52341

    multithreading - 使用 Cython 启用并行性

    linux - 一个库(.so)可以动态加载另一个用不同编译器构建的库吗

    c++ - GCC libstdc++ 配置文件模式的替代方案

    c++ - gcc 是否保证对 volatile 整数的对齐访问是原子的?

    c++ - 如何根据类模板参数专门化成员函数

    c++ - C++ "type deduction"和 Haskell "type inference"有什么区别?

    c# - 使用 MEF 的多线程 EF

    javascript - 中断驱动与事件驱动 I/O 模型

    c++ - 需要 GLIBC 2.7 版本。使用更高版本的 GLIBC 编译 C++ 代码,同时支持更早的 glibc