Boost logo

Boost Users :

From: Christopher Currie (Christopher_at_[hidden])
Date: 2003-05-14 11:22:53


This question sparked another "usage convetion" question in my memory
that came up around the office lately. I've been slow introducing the
members of my development team to a subset of Boost.Threads and trying
to get them to use RAII thinking when implementing their locks.

There seem to be two schools of thought on how to synchronize access to
a class. One school, primarly from the developers who have experience in
Java, tend to write classes that do their own mutex locking:

class CalleeLocked
{
private:
   typedef boost::mutex mutex_type;
   mutex_type m_mutex;

public:
   void synchronizedFunction() {
     mutex_type::scoped_lock lock( m_mutex );
     // ... do work ...
   }
};

The other school, to which I must admit I belong, believes that it
should be the caller's responsibility to perform the locking:

class CallerLocked
{
public:
   typedef boost::mutex mutex_type;

   void unsynchronizedFunction()
   {
     // ... do work ...
   }

   mutex_type & myMutex()
   { return m_mutex; }

private:
   mutex_type m_mutex;
}

void Caller( CallerLocked & c )
{
   CallerLocked::mutex_type::scoped_lock lock( c.myMutex() );
   c.unsynchronizedFunction();
}

The Callee lockers believe that is more important for the class to
implement the locking, because the class knows what data it has that
requires synchronized access, and that putting the locking inside the
class means that you only have to get it right once. The Caller lockers
argue that adding locks to all your class functions introduces overhead
that is unnecessary if you never share instances between threads, and
that making the locking explicit in the caller makes it somewhat easier
to prevent, or at least track down, deadlock errors.

Is there a community consensus about this? I can imagine that there are
cases where either might be appropriate, but I'd like to hear peoples
experiences with both implementations.

Thanks in advance,
Christopher Currie


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net