gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:35:33 37 4
gpt4 key购买 nike

典型的 malloc(对于 x86-64 平台和 Linux 操作系统)是在开始时天真地锁定一个互斥锁并在完成后释放它,还是在一个更聪明的方式锁定一个互斥锁?更精细的级别,从而减少锁争用?如果确实是第二种方式,它是怎么做到的?

最佳答案

glibc 2.15 操作多个分配arenas。每个竞技场都有自己的锁。当一个线程需要分配内存时,malloc()选择一个arena,锁定它,然后从中分配内存。

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

/* 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. */

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

  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 .它基于 earlier work由 Doug Lea 编写,由 Wolfram Gloger 维护。

关于c - malloc 如何在多线程环境中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10706466/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com