linux malloc 多线程,c-malloc如何在多线程环境中工作?

ptmalloc操作多个分配区域。 每个竞技场都有自己的锁。 当线程需要分配内存时,malloc()会选择一个竞技场,将其锁定并从中分配内存。

选择竞技场的机制有些复杂,旨在减少锁争用:

/* arena_get() acquires an arena and locks the corresponding mutex.

First, try the one last locked successfully by this thread. (This

is the common case and handled with a macro for speed.) Then, loop

once over the circularly linked list of arenas. If no arena is

readily available, create a new one. In this latter case, `size'

is just a hint as to how much memory will be required immediately

in the new arena. */

考虑到这一点,ptmalloc基本上看起来像这样(为简洁起见编辑):

mstate ar_ptr;

void *victim;

arena_lookup(ar_ptr);

arena_lock(ar_ptr, bytes);

if(!ar_ptr)

return 0;

victim = _int_malloc(ar_ptr, bytes);

if(!victim) {

/* Maybe the failure is due to running out of mmapped areas. */

if(ar_ptr != &main_arena) {

(void)mutex_unlock(&ar_ptr->mutex);

ar_ptr = &main_arena;

(void)mutex_lock(&ar_ptr->mutex);

victim = _int_malloc(ar_ptr, bytes);

(void)mutex_unlock(&ar_ptr->mutex);

} else {

/* ... or sbrk() has failed and there is still a chance to mmap() */

ar_ptr = arena_get2(ar_ptr->next ? ar_ptr : 0, bytes);

(void)mutex_unlock(&main_arena.mutex);

if(ar_ptr) {

victim = _int_malloc(ar_ptr, bytes);

(void)mutex_unlock(&ar_ptr->mutex);

}

}

} else

(void)mutex_unlock(&ar_ptr->mutex);

return victim;

该分配器称为ptmalloc。它基于Doug Lea的早期工作,并由Wolfram Gloger维护。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值