Using the heap in a pthread allocates >100MB of RAM

Viewed 1276

A simple pthread test case allocates the following RAM as measured by the VIRT column of top:

No pthread/heap usage: 4224 kB
Use pthread but no heap: 14716 kB
Use pthread and heap in main (but not thread): 23632 kB
Use pthread and heap in main and thread: 89168 kB

Why would so much RAM be allocated? valgrind --page-as-heap=yes shows peak heap allocation of 127MB.

I read that threads share a heap so why the big jump when using the heap from within the pthread? The code will later target an embedded system with very limited resources so understanding these allocations is quite important.

Compiled with the following (g++ version 5.4.0 on Ubuntu 16.04):

g++ -O2 -pthread thread.cpp

thread.cpp:

#include <iostream>
#include <pthread.h>
#include <unistd.h>

#define USE_THREAD
#define USE_HEAP_IN_MAIN
#define USE_HEAP_IN_THREAD

int *arr_thread;
int *arr_main;

void *use_heap(void *arg){
#ifdef USE_HEAP_IN_THREAD
    arr_thread=new int[10];
    arr_thread[0]=1234;
#endif
    usleep(10000000);
}

int main() {
    pthread_t t1;
#ifdef USE_HEAP_IN_MAIN
    arr_main=new int[10];
    arr_main[0]=5678;
#endif

#ifdef USE_THREAD
    pthread_create(&t1, NULL, &use_heap, NULL);
    pthread_join(t1,NULL);
#else
    usleep(10000000);
#endif

    return 0;
}
  • edited to use global ptrs to demonstrate the effect with -O2.
1 Answers
Related