WordCount performance

Kevin Bealer kevinbealer at gmail.com
Sat Mar 29 11:30:04 PDT 2008


Sean Kelly Wrote:

> == Quote from Benji Smith (benji at benjismith.net)'s article
> > Walter Bright wrote:
> > > Sean Kelly wrote:
> > >> Another option might be to check the thread count is greater than
> > >> 1 and only lock if it is.  Tango has a routine called thread_needLock
> > >> for this purpose, though it goes a bit farther and is true once a
> > >> thread has been created through program termination.  This avoids
> > >> problems with the situation where you have multiple threads running
> > >> and all but one terminate but memory is not yet synchronized.
> > >
> > > You have to be very careful with such schemes because they can run afoul
> > > of the notoriously difficult to comprehend "double checked locking" bug.
> > I thought the double-checked locking idiom was only buggy in the Java
> > memory model (prior to being fixed in the 1.6 JDK).
> 
> It's broken in C++ as well.  It actually works in D however, provided one uses
> 'volatile' in the right places.  I posted a demo impl a few years back either in
> this forum or in D.announce.
> 
> 
> Sean

Couldn't you two mutexes to make this work even in C++ (but I'm using D syntax for simplicity)?  The second mutex doesn't actually protect anything, but it should be a portable way to include the memory barriers.  Actually "portable" is a weasel word since all C++ locking and multithreadedness is done in platform depended libraries.

class Foo {
private:
    Object data;
    Mutex a, b;

public:
    Object getData()
    {
        if (data is null) {
            a.lock();
            if (data is null) {
                Object o = null;
                {
                    b.lock();
                    o = new Object;
                    b.unlock();
                }
                data = o;
            }
            a.unlock();
        }
        return data;
    }
};

Kevin




More information about the Digitalmars-d mailing list