views:

381

answers:

2

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.

+3  A: 

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...

metao
boost::weak_ptr is not going to work for his scenario, unless the publisher guarantees to keep the object alive until the last subscriber is done with it. this is not feasible with an async queue.
Franci Penov
@Franci Penov: +1 for your answer and this comment. The link to boost smart_ptr documentation is the one thing keeping me from downvoting this one as being not helpful.
mghie
ah, right you are. I was seduced by the idea of improved thread safety and completely forgot about the whole "its not actually holding a reference" issue!
metao
at least, yo uare a correctable idiot ;) +1 for shared_ptr.
peterchen
+3  A: 

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.

Franci Penov