55

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

4

2 回答 2

42

glibc 2.15经营多个分配领域。每个竞技场都有自己的锁。当一个线程需要分配内存时,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. 它基于Doug Lea 的早期工作,由 Wolfram Gloger 维护。

于 2012-05-22T17:07:01.060 回答
21

Doug Leamalloc使用了粗略锁定(或无锁定,取决于配置设置),其中对 // 的每个调用都malloc受到全局互斥锁的保护。这是安全的,但在高度多线程的环境中可能效率低下。reallocfree

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

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

于 2012-05-22T17:16:55.647 回答