最近我遇到了一些与内存线程相关的问题。下面的代码创建 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输出