Overview
Features
Download
Documentation
Community
Add-Ons & Services

Mutex in Delegate

Please post support and help requests here.

Mutex in Delegate

Postby BigTick » 16 May 2014, 13:57

Hi,

Looking at the Delegate.h implementation, is there any reason why disable() was implemented by clearing the receiver object (thus forcing the use of a mutex to protect concurrent access from notify) ?

Wouldn't it be better to have a mutex-free implementation with a boolean flag for enabled/disabled status ?
BigTick
 
Posts: 35
Joined: 28 Apr 2010, 21:07

Re: Mutex in Delegate

Postby BigTick » 29 May 2014, 20:27

Here is my version. Please let me know if I am missing something obvious, but I believe this one works just as well as the original Poco::Delegate, without a mutex.

Code: Select all
// copied from Poco::Delegate, without mutex
template <class TObj, class TArgs=void*>
class Delegate: public Poco::AbstractDelegate<TArgs>
{
public:
   typedef void(TObj::*NotifyMethod)(TArgs&);

   Delegate(TObj* obj, NotifyMethod method):
      _receiverObject(obj),
      _receiverMethod(method),
      _disabled(false)
   {
   }

   Delegate(const Delegate& delegate):
      Poco::AbstractDelegate<TArgs>(delegate),
      _receiverObject(delegate._receiverObject),
      _receiverMethod(delegate._receiverMethod),
      _disabled(delegate._disabled)
   {
   }

   ~Delegate()
   {
   }
   
   Delegate& operator = (const Delegate& delegate)
   {
      if (&delegate != this)
      {
         this->_receiverObject = delegate._receiverObject;
         this->_receiverMethod = delegate._receiverMethod;
         this->_disabled = delegate._disabled;
      }
      return *this;
   }

   bool notify(const void* sender, TArgs& arguments)
   {
      if (_disabled) return false;
               (_receiverObject->*_receiverMethod)(arguments);
               return true;
   }

   bool equals(const Poco::AbstractDelegate<TArgs>& other) const
   {
      const Delegate* pOtherDelegate = reinterpret_cast<const Delegate*>(other.unwrap());
      return pOtherDelegate && _receiverObject == pOtherDelegate->_receiverObject && _receiverMethod == pOtherDelegate->_receiverMethod;
   }

   Poco::AbstractDelegate<TArgs>* clone() const
   {
      return new Delegate(*this);
   }

   virtual void disable() {
      _disabled = true;
   }

protected:
   TObj*        _receiverObject;
   NotifyMethod _receiverMethod;
   volatile bool _disabled;
private:
   Delegate();
};
BigTick
 
Posts: 35
Joined: 28 Apr 2010, 21:07

Re: Mutex in Delegate

Postby alex » 02 Jun 2014, 05:01

I would agree with you; the use of volatile is pointless, though.
alex
 
Posts: 1130
Joined: 11 Jul 2006, 16:27
Location: United_States


Return to Support

Who is online

Users browsing this forum: No registered users and 1 guest

cron