【发布时间】:2017-05-01 21:15:09
【问题描述】:
似乎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(),而是在普通堆上分配空间。我想是否可以在多线程程序中关闭mmap() 对malloc() 的使用?
我的环境配置:
Thread model: posix
gcc version 5.2.0 (GCC)
Linux fsdev32 2.6.32-573.el6.x86_64
【问题讨论】:
-
为什么要禁用
mmap()ed 堆空间? -
@EOF 我们保留了大于 0x100000000000l 的地址来存储我们的系统数据。 malloc() 通过 mmap() 将破坏我们的数据,因为它也会占用这些地址。
-
@JimMa:如果您需要自己的特殊地址范围,请先映射它们。
-
不使用 mmap 就意味着只有 sbrk?
-
@Adalcar 是的。至少 malloc() 在多线程代码块中。
标签: c++ c multithreading malloc mmap