On Sun, 17 Jun 2007 08:50:29 -0700, "David Ching"
<dc@remove-this.dcsoft.com> wrote:
I find the easiest way to make MFC collections thread safe is to derive a
class such as
class CSafeMapStringToString : CMapStringToString
{
public:
AddItem (const CString &strKey, const CString &strValue);
RemoveItem (const CString &strKey);
CString LookupItem (const CString &strKey);
protected:
// all other members are protected, not accessible to caller
};
Hopefully, that implicit private inheritance is intentional. In addition,
I
don't use the MFC containers, and CMapStringToString may well pass this
test, but whenever you use private inheritance instead of containment, you
should make sure the base class has no virtual functions, because there's
no way to prevent a derived class from overriding them. (Ditto for private
virtual functions.) That's a hole in the encapsulation which can't occur
with a private member variable.
And the 3 public methods use a critical section to ensure synchronization.
That way the caller doesn't need to do anything to ensure thread safety,
which really keeps the caller code clean. I dislike code litered with all
manner of critical section usage, since it gets in the way of clearly
illustrating the purpose of the code with implementation details.
While seemingly attractive, the "synchronized wrapper" approach to thread
safety is not sufficient to protect operation sequences, classic examples
being iteration and query/update. I was reminded today of another case it
doesn't handle, dynamic creation of an object. That is, if one object X
creates another Y on demand and stores the pointer in a Y* member
variable,
the creation of the Y has to be protected. Assuming Y isn't managing
anything internal that no one else could synchronize, I'd rather do
everything myself in X, protecting both the object creation and Y function
calls with the same mutex.
Thus, to be genuinely effective, this approach must provide every
operation
the user will ever need. If it doesn't, and the user has to implement his
own synchronization, say, to handle operation sequences the class designer
didn't anticipate, it will tend to be redundant. Plus, some users won't
recognize the issue in the first place since they're using a "thread-safe"
class.
All true, Doug. Many of my solutions work 100% for my projects but are not
rigorous enough for the general case. Still, I'd rather have cleaner code
general code that is ugly. Many of the industry standards that you like to
tout are more of the latter, which is a philosophy difference. And no, I'm
not going to debate this one any further with you either.