0.1 简介
在linux中常见的malloc是glibc的malloc,经对glibc上malloc修改有适用于linux多线程的malloc即dlmalloc,还有一个ptmalloc2这两者有区别,其区别在于:
dlmalloc在子线程和父线程同时调用malloc时会有竞争,且只会有一个能够从heap中分配到空间。并且freelist data structure是被众进程共享的。
ptmalloc2可以确保不有这种竞争,而且freelist是各自进程独享自己的一个结构体。ptmalloc是per thread malloc之意。
1.malloc用例
/* 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;
}
情景1
main threadmalloc之前
sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread
Welcome to per thread arena example::6501
Before malloc in main thread
...
sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps
08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread
08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread
0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread
b7e05000-b7e07000 rw-p 00000000 00:00 0
再未用malloc时,尚未分配heap
情景2
sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$

本文介绍了glibc下的malloc,包括其在多线程环境下的工作原理,如chunk、bin和特殊chunk的概念。malloc在多线程中可能会引发竞争,而ptmalloc解决了这一问题,提供线程局部的heap。文章还探讨了malloc如何选择系统调用,并详细解释了arena、heap和chunk的数据结构,以及bin管理chunk的方式。
3948

被折叠的 条评论
为什么被折叠?



