【问题标题】:pthread_create allocates a lot of memory in Linux?pthread_create 在 Linux 中分配大量内存?
【发布时间】:2019-02-19 10:22:51
【问题描述】:

这是一个简单的例子

#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)吗?这是可配置的吗?

或者,也许而且很可能,我对虚拟内存是什么有一些误解?


详情:

我两次检查了内存使用情况,使用:

  • 生成了一个正在运行的exe的core dump,也是1.6GB;
  • valgrind --tool=massif 也确认了这个尺寸;
  • pmap -x &lt;pid&gt; 也确认了大小。

由于这个大小与堆栈的最大大小相匹配(也由/proc/&lt;pid&gt;/limits 确认),我试图使堆栈的最大大小更小。尝试使用 1 MiB,但这并没有改变任何东西。

拜托,192个线程的创建和使用,是有原因的。

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

【问题讨论】:

    标签: linux multithreading memory memory-management virtual-memory


    【解决方案1】:

    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);
    }
    

    【讨论】:

    • 哦,该死的,这真的有效!所以,它确实需要这么多内存,这确实是因为堆栈大小。谢谢,不胜感激!
    猜你喜欢
    • 2017-07-15
    • 2020-02-19
    • 1970-01-01
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多