Boost logo

Boost :

From: William Kempf (sirwillard_at_[hidden])
Date: 2000-08-08 16:05:35


Here's a rough starting point for a mutex class.

class mutex
{
private:
        // Should copying be allowed?
        mutex(const mutex&);
        operator=(const mutex&);

public:
        // Creates a new mutex. If a name is specified the mutex
        // will be created in such a way that it's sharable between
        // processes. Should the sharable functionality be included?
        // Today this would require support from the platform, and
        // if the language were to adopt it it could be complicated
        // to include this on all platforms. However, the platforms
        // I'm familiar with would allow for this and it's almost an
        // essential quality for some constructs.
        mutex(char* name=0);
        // Destoys the mutex.
        ~mutex();

        // Used to lock and unlock the mutex.
        class lock
        {
        public:
                lock(mutex& mx);
                // Throws an exception if timed out
                lock(mutex& mx, int timeout);
                ~lock();
        };

private:
        // Locks the mutex. If already locked the thread enters a
        // suspended state until it can lock the mutex. Should this
        // be recursive?
        void do_lock();
        // Attempts to lock the mutex. If the mutex can not be
        // locked within the given time frame the result is false;
        // otherwise it's true.
        bool do_lock(int timeout);
        // Unlocks the mutex.
        void do_unlock();

        // Should we have an is_locked()? If so, does it report a
        // lock by any thread or only by the current thread?
};

I put most of the things I see as questionable or issues into the
comments above. Simple useage:

mutex mx;
mutex::lock lock(mx);

or:

try
{
        mutex::lock lock(mx, 500);
}
catch (...) // or the actual exception type
{
        // We didn't get the lock within the 500 milliseconds
        // requested.
}

The lock class would allow code like the following:

mutex::lock(mx);

which would compile but not behave as some might expect. I don't
think this is a large issue, but I felt it should be pointed out.

There's likely a LOT to be discussed here, I'm just throwing it out
for a starting point. You should note that some things I left as
questions here I think have obvious answers (for instance there's not
much utility in an is_locked method), but I've asked them any way.


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