I have to share a BLOB in a multithreaded application and and I'm currently looking into shared_ptr/weak_ptr approach, but I'm not exactly sure it is correct.
There is a worker thread that creates a resource class (new CResource). CResource can be quite large, so I want to avoid extra copies.
Then there is another UI thread, I want to PostMessage with pointer to CResource to.
But the worker thread can exit faster than UI thread or vice versa. And worker has no way to know if the message has been processed.
So I'm wondering if I can create a (new shared_ptr) in worker thread, and then pass a (new weak_ptr) to postmessage function, and, if it will take a care of automatic cleanup. So, if worker thread destroys it's shared_ptr, the UI thread will return false on weak_ptr.lock, therefore there would be no need for extra synchronization and resource management.
Also what will happen if worker creates a new CResource, UI thread starts running, worker calls shared_ptr.reset(new CResource)? It seems UI thread can start reading deleted data at this point if no locking is made?
Or what if the main thread exits, and deletes it's shared_ptr during the cleanup, is the weak_ptr going to be dangling?
I'm kinda new to all this shared/weak_ptr thing, and the documentation is a little bit confusing for me for now, so excuse me if it's a dumb question.
I would be grateful if someone could tell me if it's worth investigating this option, or if there are multiple pitfalls and some old school approach is better?