Why running std :: thread with an empty function is wasting a lot of memory

I wrote a simple program that should run two threads, sort a small array (~ 4096 bytes) and write to the output file. Input data is contained in one large file (~ 4 GB). The computer has 128 MB of memory. I found that running only an empty main function uses 14 MB of memory. If you run std :: thread with an empty function application, start using ~ 8 MB per thread. BUT, if I make only one dynamic memory allocation program, it will start using approximately 64 MB per stream. I do not understand what can spend so much memory. How can I control this size? And how to allocate dynamic memory to minimize system default allocation?

  • System: Ubuntu 14.04.3
  • Compiler: gcc 4.8.4
  • Compiler option: '- std = C ++ 11 -O3 -pthread'

  • This is sample code.

    void dummy(void)
    {
        std::vector<unsigned int> g(1);
        int i = 0;
        while( i<500000000)
        {
            ++i;
        }
    }
    
    int main(void)
    {
        std::thread t1(&dummy);
        std::thread t2(&dummy);
        std::thread t3(&dummy);
        t1.join();
        t2.join();
        t3.join();
        return 0;
    }
    
+4
source share
2 answers

Each thread has its own stack. On Linux, the default stack size is 8 MB. When you start allocating memory for the first time, the heap memory allocator can actually reserve a large chunk in front. This may explain 64 MB per stream that you see.

, "", , . . VSZ ps VIRT top. Linux , , , . , , Linux , . , , RSS ps RES top. Linux , .

, , 32- , 8 , ( 2 ). ++ , C pthreads , pthread_create() pthread_attr_t, pthread_attr_setstacksize(). . fooobar.com/questions/193878/....

+7

, ulimit -s , , - , . , , , , , x86.

@Karrek SB . , , . brk sbrk, . MB - , , 4, 8, 32, 64 .., .

, , . , mallopt. . , .

0

Source: https://habr.com/ru/post/1668443/


All Articles