Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to parallelize memory allocation delete with openmp? (c++)

int **something = new int *[N];
for(int n = 0; n < N; n++)
    something[n] = new int[M];

#pragma omp parallel for
for (int n = 0; n < N; n++)
    delete[] something[n];
delete[] something;

Can I parallelize a delete process like this?

OOM killer of Linux killed my process after quite big number of loops. I tried to figure out where the memory is leaking, but I could not find where. I am not sure if these for loop delete process worked well or not.

like image 761
Mingi Kim Avatar asked Dec 14 '25 13:12

Mingi Kim


1 Answers

This is generally okay. The standard (g)libc heap must be thread-safe; otherwise, it'd be impossible to write threaded programs at all. It's also fine to allocate a buffer on one thread and free it on another.

Parallelizing heap allocations won't give you much of a speed-up, but I suspect you're asking not because you want to speed up (de-)allocation, but rather because you have some other parallel code that happens to allocate and free some buffers.

To find your leak, try running your program with valgrind.

Additionally, consider calling malloc_trim(0); after freeing large amounts of memory. This makes glibc release unused memory back to the operating system, instead of holding onto all of it for later allocations.

like image 138
Jonathan S. Avatar answered Dec 16 '25 06:12

Jonathan S.