PDA

View Full Version : What is the best way to manage memory across threads?



bughunter2
4th January 2009, 23:59
Hello,

Short version
One thread allocates memory and passes the pointer to the other thread. The other thread might free the memory block, OR it might send it back, in which case the original thread that allocated it frees it. I find this current solution messy and I want a cleaner / more centralized way of managing the memory.

Long version
I have a GUI (main) thread and a worker thread. To let them communicate with each other, I created a Communicator class.
When the worker thread needs to communicate with the GUI, it allocates an instance of the Communicator class and sends it (using a signal) to the GUI.
The GUI might send a signal back to the worker thread (passing the instance of the Communicator class back).

Now the problem is that I find this solution messy and want a better way to manage the memory. Currently I do this: either A) If the GUI sends back the signal to the worker thread, the worker thread frees it OR B) If the GUI doesn't send back the signal to the worker thread, it frees it by itself.

Source code
If you want to have a look at the source code, it can be found over here (http://trac-hg.assembla.com/mtpfileman/browser/src). In the directory 'Ui' you'll find the files Ui.cpp and UiCommunicator.cpp, and in the directory 'MtpHelper' you'll find MtpHelper.cpp, which is used as the worker thread.

wysota
5th January 2009, 00:23
Get rid of your Communicator class and use events. You can send/post arbitrary events back and forth safely between threads as long as they both run event queues. If you need to pass some specific data, implement your own custom event. Qt handles freeing memory allocated to posted events (you need to handle memory of sent events yourself so better post instead of sending especially that this is what you want anyway) so your problem will naturally disappear.

bughunter2
5th January 2009, 00:53
That's what I initially tried, but I didn't know how to send data with the event and just assumed (forgot to check the docs on it) that I needed to create a lot of events for every single message box the worker thread would want to display.

Thanks for the idea. I'll give it a go.