這兩天線上的一個服務出現了內存問題,表現在使用top查看進程的RES會間斷性的突然上升,而且從不下降。仔細review了線上的代碼,沒有發現內存泄漏,懷疑和glibc的內存分配機制有關,glibc並沒有及時將內存釋放給操作系統。
可以自行使用如下的測試代碼進行下驗證,會發現使用默認的glibc和google提供的tc_malloc,map吃掉的內存在離開自己的scope后並沒有吐給操作系統,使用jemalloc沒有如上問題。線上的代碼已經重新用jemalloc編譯推動上線了,還處在觀察階段。
#include <malloc.h> #include <map> #include <iostream> #include <stdlib.h> //#include "google/malloc_extension.h" void testmap() { std::cout << "*************1 malloc_stats****************" << std::endl; malloc_stats(); std::cout << std::endl; std::map<int, int> testmap; for(int i = 0; i != 10000000; i++) { testmap[i] = i; } std::cout << "*************2 malloc_stats****************" << std::endl; malloc_stats(); std::cout << std::endl; testmap.clear(); std::cout << "*************3 malloc_stats****************" << std::endl; malloc_stats(); std::cout << std::endl; } int main() { //static const int DEFAULT_MMAP_THRESHOLD = 0; //::mallopt(M_MMAP_THRESHOLD, DEFAULT_MMAP_THRESHOLD); testmap(); //MallocExtension::instance()->ReleaseFreeMemory(); sleep(20); std::cout << "*************4 malloc_stats****************" << std::endl; malloc_stats(); std::cout << std::endl; }
如下,記錄下在網上查到的一些資料:
jemalloc
更好的內存管理-jemalloc (^_^給程序員最后的免費的午餐)
tcmalloc
TCMalloc : Thread-Caching Malloc
glibc
glibc內存管理ptmalloc2源代碼分析 (大殺器,慎入,一份130頁的pdf文檔)
STL
實際應用
Will malloc implementations return free-ed memory back to the system?
文章最后,對貴淘寶等的無私分享精神表示感謝!!