开发者

boost signals - How control lifetime of objects sent to subscribers? Smart pointers?

I am using boost::signals2 under Red Hat Enterprise Linux 5.3.

My signal creates an object copy and sends it's pointer to subscribers. This was implemented for thread safety to prevent the wor开发者_如何学编程ker thread from updating a string property on the object at the same time it is being read ( perhaps I should revisit the use of locks? ).

Anyway, my concern is with multiple subscribers that dereference the pointer to the copied object on their own thread. How can I control object lifetime? How can I know all subscribers are done with the object and it is safe to delete the object?

typedef boost::signals2::signal< void ( Parameter* ) > signalParameterChanged_t;
signalParameterChanged_t    m_signalParameterChanged;

// Worker Thread - Raises the signal
void Parameter::raiseParameterChangedSignal()
{
      Parameter* pParameterDeepCopied = new Parameter(*this);
      m_signalParameterChanged(pParameterDeepCopied);
}
// Read-Only Subscriber Thread(s) - GUI (and Event Logging thread ) handles signal
void ClientGui::onDeviceParameterChangedHandler( Parameter* pParameter)
{
      cout << pParameter->toString() << endl;
      delete pParameter;  // **** This only works for a single subscriber !!!
}

Thanks in advance for any tips or direction,

-Ed


If you really have to pass Parameter by pointer to your subscribers, then you should use boost::shared_ptr:

typedef boost::shared_ptr<Parameter> SharedParameterPtr;
typedef boost::signals2::signal< void ( SharedParameterPtr ) > signalParameterChanged_t;
signalParameterChanged_t    m_signalParameterChanged;

// The signal source
void Parameter::raiseParameterChangedSignal()
{
      SharedParameterPtr pParameterDeepCopied = new Parameter(*this);
      m_signalParameterChanged(pParameterDeepCopied);
}
// The subscriber's handler
void ClientGui::onDeviceParameterChangedHandler( SharedParameterPtr pParameter)
{
      cout << pParameter->toString() << endl;
}

The shared parameter object sent to your subscribers will be automatically deleted when its reference count becomes zero (i.e. it goes out of scope in all the handlers).

Is Parameter really so heavyweight that you need to send it to your subscribers via pointer?

EDIT:

Please note that using shared_ptr takes care of lifetime management, but will not relieve you of the responsibility to make concurrent reads/writes to/from the shared parameter object thread-safe. You may well want to pass-by-copy to your subscribers for thread-safety reasons alone. In your question, it's not clear enough to me what goes on thread-wise, so I can't give you more specific recommendations.

Is the thread calling raiseParameterChangedSignal() the same as your GUI thread? Some GUI toolkits don't allow concurrent use of their API by multiple threads.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜