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

pyt*_*nic 48 c linux malloc gcc x86-64

典型的malloc(对于x86-64平台和Linux操作系统)是否在开始时天真地锁定互斥锁并在完成时释放它,或者是否以更精巧的方式更智能地锁定互斥锁,从而减少锁争用?如果它确实是第二种方式,它是如何做到的?

NPE*_*NPE 38

glibc 2.15经营多个分配领域.每个竞技场都有自己的锁.当一个线程需要分配内存时,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. */
Run Code Online (Sandbox Code Playgroud)

考虑到这一点,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;
Run Code Online (Sandbox Code Playgroud)

调用此分配器ptmalloc.它基于Doug Lea的早期工作,由Wolfram Gloger维护.


Ada*_*eld 20

Doug Lea的malloc使用粗锁(或无锁定,这取决于配置设置),在那里每一个电话malloc/ realloc/ free是一个全球性的互斥体的保护.这是安全的,但在高度多线程环境中可能效率低下.

ptmalloc3,这是目前malloc在大多数Linux系统上使用的GNU C库(libc)中的默认实现,具有更细粒度的策略,如aix的答案中所述,它允许多个线程同时安全地分配内存.

nedmalloc是另一个独立的实现,它声称甚至比ptmalloc3各种其他分配器更好的多线程性能.我不知道它是如何工作的,似乎没有任何明显的文档,所以你必须检查源代码,看看它是如何工作的.

  • @R..:乍一看确实有点可疑,但它有源代码,因此您可以自己对其进行基准测试(我还没有这样做)。Doug Lea 还在“dlmalloc.c”的注释中说“如果您在并发程序中使用 malloc,请考虑使用 nedmalloc 或 ptmalloc”。所以我认为这可能是合法的。 (2认同)