pthread_create 在 Linux 中分配了很多内存?

pthread_create allocates a lot of memory in Linux?

这是一个简单的例子

#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 KiBVIRT!我知道这不是常驻内存,但对于创建单个线程来说,这仍然是一个巨大的内存量。

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

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


详情:

我双重检查内存使用情况,使用:

由于这个大小与堆栈的最大大小相匹配(/proc/<pid>/limits 也证实了这一点),我试图使堆栈的最大大小更小。尝试使用 1 MiB,但这并没有改变任何东西。

请抛开192个线程的创建和使用,这是有原因的。

抱歉混合使用了 C 和 C++ - 最初尝试使用 std::thread 结果相同。

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