似乎在多线程程序中,malloc()
更倾向于使用mmap()
来分配空间。我尝试设置M_TRIM_THRESHOLD
和M_MMAP_MAX
以关闭mmap
的使用,但失败了:
// Turn off malloc trimming.
mallopt(M_TRIM_THRESHOLD, -1);
// Turn off mmap usage.
mallopt(M_MMAP_MAX, 0);
一个简单的测试代码示例如下:
#include <malloc.h>
#include <cassert>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void alloc_assert()
{
// Turn off malloc trimming.
mallopt(M_TRIM_THRESHOLD, -1);
// Turn off mmap usage.
mallopt(M_MMAP_MAX, 0);
void* p = malloc(100);
printf("size_t(p): %zu\n", size_t(p));
assert(size_t(p) < 0x100000000000l);
}
void* thread_func(void *arg)
{
alloc_assert();
pthread_exit(NULL);
return NULL;
}
int main()
{
pthread_t thr[2];
int data = 0;
// Multi-thread enabled.
if (pthread_create(&thr[0], NULL, &thread_func, (void*) &data) != 0)
{
printf("Create thread error\n");
}
pthread_join(thr[0], NULL);
//alloc_assert();
return 0;
}
以下是输出结果:
size_t(p): 140154111002816
a.out: main.cpp:37: void alloc_assert(): Assertion `size_t(p) < 0x100000000000l' failed.
[1] 154060 abort ./a.out
malloc()
在高地址分配空间,而不是普通堆地址。然而,如果我们更改main()
中的代码如下:
int main()
{
alloc_assert();
return 0;
}
输出结果为:
size_t(p): 31775776
使用malloc()
分配空间的方式是在普通堆上分配,而不是使用mmap()
。我想知道在多线程程序中是否有可能关闭malloc()
对mmap()
的使用。
我的环境配置:
Thread model: posix
gcc version 5.2.0 (GCC)
Linux fsdev32 2.6.32-573.el6.x86_64