Search code examples
multithreadingc++11shared-ptr

Shared resource management in multithreaded application shared_ptr?


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?


Solution

  • weak_ptr is typically used to break cycles in interdependent data structures.

    I believe from the description you provided that this will work. Once weak_ptr::lock succeeds, you are good until you let the returned shared_ptr go out of scope.

    I don't understand why you don't just give the UI thread a shared_ptr of its own, though. Then you don't have to worry about the shared_ptr in the worker thread disappearing and taking your BLOB access with it. Data sharing like this is precisely what shared_ptr is ideal for.