Question

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?

Was it helpful?

Solution

You can implement the task cancellation pattern.

You can find this pattern in Intel TBB, Microsoft C++ PPL, Microsoft C# TPL, and many other parallel frameworks.

The task cancellation pattern consist of shared flag and shared data. The flag itself can be implemented as a std::atomic<bool>. Either thread can set it. Any code that spends significant CPU time working on the data should check this flag occasionally, and to wrap up or abandon the work if it is set to true. In addition to wrapping up, it should also release the std::shared_ptr<T> to the shared data. Because the thread that requests cancellation is presumably also releasing the shared data, the outcome is that the shared data will indeed be released as quickly as possible after cancellation once both threads had time to acknowledge and respond to that.

In some cases, you may use std::weak_ptr<T>, if it is appropriate for some of the threads to unilaterally cause the data to be discarded. Note that, any code that want to access the data guarded by a std::weak_ptr<T> must do so by requesting and keeping a std::shared_ptr<T> from it during the access. Otherwise, there will be a multithreaded use-after-free race condition (freeing during use) defect.

There are other approaches, such as manager object, singleton (which is a static manager), message-passing architecture, etc.

Licensed under: CC-BY-SA with attribution
scroll top