Question

I would like to implement a simple Publish/Subscribe pattern where:

A single publisher publishes a token (a pointer to an object) to its subscribers. Publisher and subscribers are all independent threads. I plan to add thread-safe queue to each of the subscriber such that Publisher can keep distributing the tokens to the subscribers while they are processing the tokens.

As you can see, that means all of the subscribers actually share the same pointers (note: subscribers cannot modify the pointed object in anyway, so no problem there). Once the shared pointer is not used by any of the subscribers anymore, it would be really nice if the pointer could auto-delete itself once the last subscriber thread is done with it.

Is this a good place to use a smart pointer? If so, which ones of the smart pointers should I use?

I develop on Windows with MSVC2008, and am using Intel TBB, Boost and Qt.

Was it helpful?

Solution

If I assume your design is viable (it smells funny with zero context, but may well be correct), boost::shared_ptr might be the way to go.

http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/smart_ptr.htm

Edit: switch to ::shared_ptr from ::weak_ptr, because I am an idiot...

OTHER TIPS

What you describe is the classic COM pattern for object lifetime control. You need a smart pointer that keeps reference counter on the object - boost::shared_ptr, boost::intrusive_ptr or ATL's CComPtr class. I would suggest shared_ptr, as the other two will require your own implementation of the ref counting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top