programing

멀티 스레드 환경에서 malloc은 어떻게 작동합니까?

javaba 2022. 7. 27. 23:51
반응형

멀티 스레드 환경에서 malloc은 어떻게 작동합니까?

표준적인 기능하고 있는가?malloc(x86-64 플랫폼 및 Linux OS의 경우) 처음에 뮤텍스를 순진하게 잠그고 실행한 후 해제하는가, 아니면 더 현명한 방법으로 뮤텍스를 잠그면 잠금 경합이 감소합니까?만약 그것이 정말로 두 번째 방법으로 작동한다면, 어떻게 작동할까요?

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;

이 할당자는 라고 불립니다.더그 리의 초기 작품을 바탕으로 울프램 글로거가 관리하고 있습니다.

Doug Lea가 사용한 거친 잠금(또는 구성 설정에 따라서는 잠금이 없음)으로, 모든 통화는 다음과 같이 처리됩니다.malloc/realloc/free는 글로벌 뮤텍스에 의해 보호됩니다.이는 안전하지만 고도로 멀티 스레드화된 환경에서는 비효율적일 수 있습니다.

디폴트입니다ptmalloc3.malloc오늘날 대부분의 Linux 시스템에서 사용되는 GNU C 라이브러리(libc)의 구현은 여러 스레드가 동시에 메모리를 안전하게 할당할 수 있도록 하는 보다 세분화된 전략을 가지고 있습니다.

nedmalloc 또 하나의 독립된 구현으로 멀티스레드 퍼포먼스가 보다 우수성을 자랑합니다.ptmalloc3기타 다양한 할당자.어떻게 작동하는지도 모르고 명확한 문서도 없는 것 같기 때문에 소스코드를 체크하여 어떻게 작동하는지 확인해야 합니다.

언급URL : https://stackoverflow.com/questions/10706466/how-does-malloc-work-in-a-multithreaded-environment

반응형