小编典典

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

linux

典型的malloc(对于x86-64平台和Linux
OS)是在开始时幼稚地锁定互斥锁并在完成后将其释放,还是以更巧妙的方式将互斥锁锁定在更精细的级别,从而减少了锁争用?如果确实采用第二种方法,那么该如何做?


阅读 530

收藏
2020-06-03

共1个答案

小编典典

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

考虑到这一点,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维护。

2020-06-03