Search code examples
clinuxmultithreadingglibc

malloc in child thread cost too much virtual memory


void * thread_client_timeout_check(void *arg)
{
    pthread_attr_t attr;size_t size;
    pthread_attr_init(&attr);
    pthread_attr_getstacksize(&attr, &size);
    printf("pthread stacksize: %d\n", size);
    malloc(1);
}

main thread create the child and pause.

int main()
{
    pthread_t pid;
    pthread_create(&pid, NULL, thread_client_timeout_check, NULL);
    pause();
}
  1. before pthread_create, top virt is 0.3m
  2. after pthread_create, top virtis8.3m (pthread stack size is 8m)
  3. after malloc(1),top virtis72.3m

Why malloc(1) will get 54m virtual memory from kernel?


Solution

  • In a multithreaded program, glibc 2.10+ creates a number of malloc pools in order to reduce false sharing and thus improve scalability. The result is that as of glibc 2.10, the virtual memory usage will be much higher. But as address space is cheap, or more or less free on 64-bit architectures, it's really nothing to worry about.

    See https://udrepper.livejournal.com/20948.html