Boost logo

Boost :

From: Alexander Terekhov (terekhov_at_[hidden])
Date: 2001-08-07 12:44:21


> If you click on just the right sequence, and your machine is set up just
> right, and blah blah blah you can actually see the files rendered
> correctly. But to make it easier to get the whole package for local
> reading, I've uploaded the following:
>
> http://groups.yahoo.com/group/boost/files/threads/thread_doc_snapshot.zip

faq.html:

>> // For assignment we need to synchronize both objects!
>> const counter& operator=(const counter& other)
>> {
>> boost::mutex::scoped_lock scoped_lock(m_mutex);
>> boost::mutex::scoped_lock scoped_lock(other.m_mutex);
>> m_value = other.m_value;
>> return *this;
>> }

is rather dangerous; potential deadlock for

    thread A: thread B:
    ============= =============
    cntr1 = cntr2; cntr2 = cntr1;

or even (with non-recursive default mutexes):

    thread A:
    =============
    cntr1 = cntr1;

how about something like:

   const counter& operator=(const counter& other)
   {
      if ( this != &other ) {
         boost::mutex::scoped_lock scoped_lock1(this < &other ? m_mutex :
other.m_mutex);
         boost::mutex::scoped_lock scoped_lock2(this < &other ?
other.m_mutex : m_mutex);
         m_value = other.m_value;
      }
      return *this;
   }

or (with race condition; might be ok in some cases):

   const counter& operator=(const counter& other)
   {
      if ( this != &other ) {

         int value;

         {
             boost::mutex::scoped_lock scoped_lock(other.m_mutex);
             value = other.m_value;
         }
         {
             boost::mutex::scoped_lock scoped_lock(m_mutex);
             m_value = value;
         }

      }
      return *this;
   }

regards,
alexander.
<still hating _lock name/lack of "cleanup handler" semantics>


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk