代码之家  ›  专栏  ›  技术社区  ›  Kiril Kirov

pthread\u create在Linux中分配大量内存?

  •  3
  • Kiril Kirov  · 技术社区  · 6 年前

    #include <iostream>
    #include <thread>
    #include <vector>
    #include <chrono>
    
    void* run(void*)
    {
        while (true)
            std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    
    int main()
    {
        std::vector<pthread_t> workers(192);
    
        for (unsigned i = 0; i < workers.size(); ++i)
            pthread_create(&workers[i], nullptr, &run, nullptr);
    
        pthread_join(workers.back(), nullptr);
    }
    

    top 显示 1'889'356 KiB VIRT ! 我知道这不是驻留内存,但对于单个线程创建来说,这仍然是巨大的内存量。

    创建一个线程真的需要这么高的内存(本例中是8MiB)吗?这是可配置的吗?

    或者,也许,最有可能的是,我误解了什么是虚拟记忆?


    细节:

    • 生成了 core dump 在运行的exe中,它也是1.6GB;
    • valgrind --tool=massif 也证实了这个尺寸;
    • pmap -x <pid> 也证实了尺寸。

    因为此大小与堆栈的最大大小相匹配(也由 /proc/<pid>/limits

    请把192个线程的创建和使用放在一边,这背后是有原因的。

    对不起,混合C和C++最初尝试过 std::thread 结果是一样的。

    1 回复  |  直到 6 年前
        1
  •  1
  •   MikeCAT    6 年前

    pthread_attr_setstacksize() 线程属性对象必须作为的第二个参数传递 pthread_create() .

    #include <iostream>
    #include <thread>
    #include <vector>
    #include <chrono>
    
    void* run(void*)
    {
        while (true)
            std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    
    int main()
    {
        std::vector<pthread_t> workers(192);
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_setstacksize(&attr, 16384);
    
        for (unsigned i = 0; i < workers.size(); ++i)
            pthread_create(&workers[i], &attr, &run, nullptr);
    
        pthread_join(workers.back(), nullptr);
    }