本文章引用
堆內存是一個很有意思的領域典蝌,這樣的問題:
henan.qq.com/zt/2018/dyzb/qi angwang.htm?from=singlemessage&isappinstalled=0
堆內存是如何從內核中分配的逐样?
內存管理效率怎樣?
它是由內核、庫函數(shù)透典,還是應用本身管理的滤奈?
堆內存可以開發(fā)嗎摆昧?
我也困惑了很久,但是直到最近我才有時間去了解它蜒程。下面就讓我來談談我的研究成果绅你。開源社區(qū)提供了很多現(xiàn)成的內存分配器(memory allocators ):
- dlmalloc – General purpose allocator
- ptmalloc2 – glibc
- jemalloc – FreeBSD and Firefox
- tcmalloc – Google
- libumem – Solaris
- …
每一種分配器都宣稱自己快(fast)、可拓展(scalable )昭躺、效率高(memory efficient)忌锯!但是并非所有的分配器都適用于我們的應用。內存吞吐量大(memory hungry)的應用程序的性能很大程度上取決于內存分配器的性能领炫。
在這篇文章中偶垮,我將只談論「glibc malloc」內存分配器。為了更好地理解「glibc malloc」帝洪,我會聯(lián)系最近的源代碼针史。
歷史:[ptmalloc2](http://www.malloc.de/en/) 基于 [dlmalloc](http://g.oswego.edu/dl/html/malloc.html) 開發(fā),并添加了對多線程的支持碟狞,于 2006 年公布啄枕。在公布之后,ptmalloc2 被整合到 glibc 源代碼中族沃,此后 ptmalloc2 所有的修改都直接提交到 glibc 的 malloc 部分去了频祝。因此,ptmalloc2 的源碼和 glibc 的 malloc源碼有很多不一致的地方脆淹。(譯者注:1996 年出現(xiàn)的 dlmalloc 只有一個主分配區(qū)常空,為所有線程所爭用,1997 年發(fā)布的 ptmalloc 在 dlmalloc 的基礎上引入了非主分配區(qū)的支持盖溺。 )
系統(tǒng)調用
在之前的文章中提到過malloc的內部調用為 brk 或 mmap 漓糙。
譯者注:其中有一張關于虛擬地址空間分布的圖片,我覺得很有助于本篇文章的理解烘嘱,因此把它放在此處昆禽。
線程處理
Linux 的早期版本使用 dlmalloc 為默認內存分配器蝗蛙,但是因為 ptmalloc2 提供了多線程支持,所以 Linux 后來采用 ptmalloc2 作為默認內存分配器醉鳖。多線程支持可以提升內存分配器的性能捡硅,進而間接提升應用的性能。
在 dlmalloc 中盗棵,當有兩個線程同時調用 malloc 時壮韭,只有一個線程能夠訪問臨界區(qū)(critical section)——因為「空閑列表數(shù)據(jù)結構」(freelist data structure)被所有可用線程共享。正如此纹因,使用 dlmalloc 的多線程應用會在內存分配上耗費過多時間喷屋,導致整個應用性能的下降。
而在 ptmalloc2 中瞭恰,當有兩個線程同時調用 malloc 時逼蒙,內存均會得到立即分配——因為每個線程都維護著一個獨立的「堆段」(heap segment),因此維護這些堆的「空閑列表數(shù)據(jù)結構」也是獨立的寄疏。這種為每個線程獨立地維護堆和「空閑列表數(shù)據(jù)結構」的行為就稱為 per thread arena。
/* Per thread arena example. */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
void* threadFunc(void* arg) {
printf("Before malloc in thread 1\n");
getchar();
char* addr = (char*) malloc(1000);
printf("After malloc and before free in thread 1\n");
getchar();
free(addr);
printf("After free in thread 1\n");
getchar();
}
int main() {
pthread_t t1;
void* s;
int ret;
char* addr;
printf("Welcome to per thread arena example::%d\n",getpid());
printf("Before malloc in main thread\n");
getchar();
addr = (char*) malloc(1000);
printf("After malloc and before free in main thread\n");
getchar();
free(addr);
printf("After free in main thread\n");
getchar();
ret = pthread_create(&t1, NULL, threadFunc, NULL);
if(ret)
{
printf("Thread creation error\n");
return -1;
}
ret = pthread_join(t1, &s);
if(ret)
{
printf("Thread join error\n");
return -1;
}
return 0;
}
輸出分析
在主線程 malloc 之前
在如下的輸出里我們可以看到僵井,這里還 沒有「 堆段」 也沒有 「每線程椛陆兀」(per-thread stack),因為 thread1 還沒有創(chuàng)建批什!