Imagine the following pattern: you have a window with information that needs to be updated asynchronously. You launch and detach a thread to handle fetching the information, but while the information is being fetched the window is closed and unloaded from memory. When the background thread goes to update the information in the window's memory, the memory has already been deallocated and a segmentation fault occurs.
I'm programming in C++, so I could wrap the memory being updated in a std::shared_ptr
, but this means the memory has to stay allocated for the duration of the background task, and I'd rather free it immediately. Is there a better way to solve this problem?
shared_ptr
, and for freeing the shared memory when the window is closed, it is obviously necessary to cancel the background thread beforehand. And that leads directly to rwong's answer.