Search code examples
c++design-patternsqtmemory-leaksworker-thread

How to prevent memory leaks while cancelling an operation in a worker thread?


Currently i am working on a desktop application which consists mathematical analysiss.I am using qt for GUI and project written in c++. When user starts an analysis, i open a worker thread and start a progress bar.Everything is ok up to now, problem starts when user cancels operation.Operation is complex, i am using several functions and objects, i allocate/deallocate memory at several times.I want to learn what should i do for recovering in cancel operation.Because there can be memory leaks.Which pattern or method i should use to be robust and safe for cancelling operation?

My idea is throwing an exception, but operation is really complex so should i put try-catch to all of my functions or is there a more generic way, pattern..

Edit: Problem is my objects are transfered between scopes, so shared_ptr or auto_ptr doesnt solve my problem, Flag idea can be, but i think it requires so much code and there should be an easy way.


Solution

  • A pretty common way to close down worker threads, is to mark it with a flag, and let the worker thread inspect this flag at regular intervals. If marked, it should discontinue its workflow, clean up and exit.

    Is that a possibility in your situation?