I have a threaded pipe-and-filter implementation where I want to use thread-local copies in one of my filters. I do not implement a run loop myself. Instead, the base Filter class calls a process() method on each of the filters whenever it gets data to be processed.
I have two issues with using thread_locals in this scenario: 1) I cannot declare thread_locals within the process() method, because the point is to reuse the thread locals whenever the process() method is called.
Example code below:
void process(SomeInput in) {
thread_local SomeClass* someClass = nullptr;
if (someClass == nullptr) someClass = new SomeClass(params);
// do stuff here...
}
So above I initialize a thread_local instance of SomeClass. But I do not deallocate it, because process() will be called by the same thread's run loop whenever new data arrives. Obviously, it the classes will never get freed. Bad.
2) I've added a threadCleanup() method to the filter implementation which gets now called whenever a filter is stopped (and it's thread(s) are stopped). Though that would require to declare thread_local member variables like:
class SomeFilter : public Filter <...> {
// ...
private:
thread_local SomeClass* _someClass;
}
But that doesn't work with classes and throws: "thread_local is only allowed on variable declarations"
What is the proper way to declare, allocate and deallocate thread-locals in such scenario?