gpt4 book ai didi

linux - 关于glibc中malloc实现的问题

转载 作者:行者123 更新时间:2023-12-05 04:22:40 27 4
gpt4 key购买 nike

我正在阅读 glibc 的源代码。
在函数 void *__libc_malloc(size_t bytes) 中:

void *__libc_malloc(size_t bytes) {
mstate ar_ptr;
void *victim;
_Static_assert(PTRDIFF_MAX <= SIZE_MAX / 2, "PTRDIFF_MAX is not more than half of SIZE_MAX");
if (!__malloc_initialized) ptmalloc_init();

...
}

表明如果第一个线程被创建,它调用ptmalloc_init(),并将thread_arena链接到main_arena,并设置__< em>malloc_initialized 为真。
另一方面,第二个线程被 ptmalloc_init() 中的以下代码阻塞:

static void ptmalloc_init(void) {
if (__malloc_initialized) return;
__malloc_initialized = true;
thread_arena = &main_arena;
malloc_init_state(&main_arena);
...

因此第二个线程的thread_arena为NULL,需要mmap()额外的arena。
我的问题是:
似乎有可能导致竞争条件,因为 __malloc_initialized 没有任何锁,并且第一个线程和第二个线程的 thread_arenas 可能都链接到 main_arena,为什么不使用锁来保护 __malloc_initialized

最佳答案

It seems possible to cause race condition because there's no any lock with __malloc_initialized

当程序仍然是单线程时,它不可能1在没有调用分配例程(因此ptmalloc_init)的情况下创建第二个运行线程。

正因为如此,ptmalloc_init 可以假设它在只有一个线程时运行。


1为什么不可能?因为创建一个线程自身调用了calloc

例如,在这个程序中:

#include <pthread.h>

void *fn(void *p) { return p; }
int main()
{
pthread_t tid;
pthread_create(&tid, NULL, fn, NULL);
pthread_join(tid, NULL);
return 0;
}

ptmalloc_init 在这里被调用(此时只有一个线程存在):

Breakpoint 2, ptmalloc_init () at /usr/src/debug/glibc-2.34-42.fc35.x86_64/malloc/arena.c:283
283 if (__malloc_initialized)
(gdb) bt
#0 ptmalloc_init () at /usr/src/debug/glibc-2.34-42.fc35.x86_64/malloc/arena.c:283
#1 __libc_calloc (n=17, elem_size=16) at malloc.c:3526
#2 0x00007ffff7fdd6c3 in calloc (b=16, a=17) at ../include/rtld-malloc.h:44
#3 allocate_dtv (result=result@entry=0x7ffff7dae640) at ../elf/dl-tls.c:375
#4 0x00007ffff7fde0e2 in __GI__dl_allocate_tls (mem=mem@entry=0x7ffff7dae640) at ../elf/dl-tls.c:634
#5 0x00007ffff7e514e5 in allocate_stack (stacksize=<synthetic pointer>, stack=<synthetic pointer>,
pdp=<synthetic pointer>, attr=0x7fffffffde30)
at /usr/src/debug/glibc-2.34-42.fc35.x86_64/nptl/allocatestack.c:429
#6 __pthread_create_2_1 (newthread=0x7fffffffdf58, attr=0x0, start_routine=0x401136 <fn>, arg=0x0)
at pthread_create.c:648
#7 0x0000000000401167 in main () at p.c:7

关于linux - 关于glibc中malloc实现的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73916789/

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