-1

最近我遇到了一些与内存线程相关的问题。下面的代码创建 5 个线程,每个线程 push_back 到向量 500'000'000 int 值。在带有 push_back 的循环结束后,程序仍然使用 ~375M 的虚拟内存,这是我的问题,为什么进程仍然使用这么多内存?

我正在使用 g++ (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0

#include <chrono>
#include <iostream>
#include <thread>
#include <vector>

using namespace std;
  

void joinAll(vector<thread>& arg)
{
    for(auto& item : arg) item.join();
}

int main()
{

    vector<thread> threads;
    
    for(int i=0; i<5; ++i)
    {
        threads.emplace_back([](){
            
            {   // block
                vector<int> data;
                
                for(int idx=0; idx<500'000'000; ++idx)
                {
                        data.push_back(idx);    
                }
            }   // end of block
            
            cout<<"loop is over\n";
            
            std::this_thread::sleep_for(chrono::seconds(5));
            
            });
    }    
    
    cout<<"wait in main\n";  
    
    std::this_thread::sleep_for(std::chrono::seconds(5));
    
    joinAll(threads);
        
}

图像呈现htop输出

在此处输入图像描述

4

1 回答 1

1

进程不需要在不再使用时将其内存返回给操作系统。如果有这样的要求,也是非常低效的。

另外,让我们快速分析一下程序的内存需求。假设典型情况int是 4 个字节,并假设您的线程并行运行并在相似的时间完成,那么您的程序仅需要大约 2.5GB 用于您vector的 s,更不用说线程本身和任何其他进程内存的内存需求了。您只看到约 375MB 的使用量这一事实表明该进程的内存大部分已返回给操作系统。

于 2021-02-07T21:43:01.337 回答