【发布时间】:2020-05-23 08:57:15
【问题描述】:
我正在开发一个使用大量线程的程序,每个线程在堆中分配几兆字节的内存。当这些线程结束时,程序会保留大部分 RAM。
这是一个代码示例,在 500 个线程中分配和释放 1 MB,显示了这个问题:
#include <future>
#include <iostream>
#include <vector>
// filling a 1 MB array with 0
void task() {
const size_t S = 1000000;
int * tab = new int[S];
std::fill(tab, tab + S, 0);
delete[] tab;
}
int main() {
std::vector<std::future<void>> threads;
const size_t N = 500;
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout << "Starting threads" << std::endl;
for (size_t i = 0 ; i < N ; ++i) {
threads.push_back(std::async(std::launch::async, [=]() { return task(); }));
}
for (size_t i = 0 ; i < N ; ++i) {
threads[i].get();
}
std::cout << "Threads ended" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(25));
return 0;
}
在我的电脑上,这段代码只是用g++ -o exe main.cpp -lpthread 构建的,在消息“开始线程”之前使用了 1976 kB,在消息“线程结束”之后使用了 419 MB。这些值只是示例:当我多次运行程序时,我可以得到不同的值。
我已经尝试过 valgrind / memcheck,但它没有检测到任何泄漏。
我注意到用互斥锁锁定“std::fill”操作似乎可以解决这个问题(或大大减少它),但我不认为这是一个竞争条件问题,因为没有共享内存这里。我猜互斥锁只是在线程之间创建一个执行顺序,从而避免(或减少)内存泄漏的情况。
我正在使用带有 GCC 7.4.0 的 Ubuntu 18.04。
感谢您的帮助。
奥雷利安
【问题讨论】:
标签: c++ multithreading memory-leaks