Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing memory across threads

Is it a bad practice to free memory across threads? Such that a thread allocates memory and, after exiting, passes the pointer to the main thread to free the memory. I feel like the answer is yes but I'm just wondering.

The purpose of this in my code is so that the main thread can do some other stuff with the memory before it gets freed. There's plenty of workarounds, in my case, which I'm totally fine with using. But having a thread return void * to a block of memory can, in my case, make the code pretty convenient.

EDIT: I know there are no technical faults in doing this.

like image 484
tay10r Avatar asked Apr 14 '13 04:04

tay10r


3 Answers

It's not wrong for a thread to pass control of memory it has allocated to another thread. For example, in a producer/consumer model, it would be very reasonable for the producer thread to allocate memory for whatever it is that it produces, and then hand control over that memory to the consumer thread for the consumer thread to use and release.

like image 103
Jonathan Leffler Avatar answered Oct 13 '22 19:10

Jonathan Leffler


It's not "bad practice" as long as it makes sense to your data flow model, and particular to the requirements your program has on object lifetimes, but it can incur costs. Many modern allocators use thread-local arenas, where allocating and freeing an object in the same thread incurs no synchronization penalty, but freeing it in a different thread forces synchronization or incurs other costs. I would not change your design for this reason unless it's a major bottleneck, but with this implementation-detail in mind you could also consider other designs, such as having the thread store its output in a buffer provided by the parent thread in the argument to the thread start function.

like image 5
R.. GitHub STOP HELPING ICE Avatar answered Oct 13 '22 20:10

R.. GitHub STOP HELPING ICE


All threads share a common heap. It doesn't matter which thread allocates or frees the memory, as long as the other threads are done using the memory when it gets freed.

like image 2
Barmar Avatar answered Oct 13 '22 19:10

Barmar