in reply to Re^8: ithreads memory leak
in thread ithreads memory leak

It looks like, memory requested by XS code is eventually returned to OS (right?).

No. Not in general.

Under Windows(*), if you request a large (from memory it was >1MB; but that may have changed) contiguous chunk of memory; then instead of calling the C runtime malloc(), it goes direct to the OS and uses VirtualAlloc() to allocate a distinct chunk of virtual memory from the system memory pool rather than taking a chunk from the process' heap.

Because that single large allocation is only used for that single purpose -- a very large string or the base allocation of a large array or hash -- when the owning Perl entity (scalar/hash/array) is freed, the entire virtual allocation can be returned to the OS.

This includes the stacks allocated to threads which under the defaults, often predominates the memory used by a thread -- see threads module stack_size parameter for how to vastly reduce the memory consumption of threads. Most of my threaded coded uses nothing more than a 4kB stack rather than the default of 1MB.

But all allocations less than that 1MB limit -- which for most Perl programs is the vast majority of allocations -- come from process heap via the CRT malloc(), and they are never returned to the OS until the process ends.

Your program is unusual in that you are apparently using both threads -- which tend to allocate large chunks for stacks -- and pdl with very large piddles, which are allocated as single contiguous chunks. That combination when running on windows gives you a distorted view of Perl's ability to return memory to the OS.

*I seem to recall seeing mention that Perl now(v5.1something) does a similar thing -- bypassing malloc() for large contiguous allocations -- under *nix; but I couldn't swear to it.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^10: ithreads memory leak
by vr (Curate) on Dec 29, 2016 at 11:25 UTC
    Interesting. Thank you for explanation. Yet, in example above, the "large allocation" for array was done both in main thread and second thread. Memory was returned to OS only when thread was joined, and not when array was destroyed. I'm also trying now to avoid single large allocation, in created thread. (E.g., pushing to array in loop.) Again, when thread is joined, memory is back to OS.