Boost logo

Boost :

From: Michael Glassford (glassfordm_at_[hidden])
Date: 2004-07-16 12:54:32


In an attempt to reconcile the different preferences and ideas expressed
in this thread, here's a thought experiment for mutex & lock
unification. What if the mutex and lock classes were policy-based,
allowing users to choose the interface they want and supplying a typedef
or two for the "most common" or "approved" variations?

Example below (note that I haven't tried to implement multiple policies
elegantly). Hopefully it could be expanded to include recursive,
checked, read/write, etc.

//---------- Mutex ----------//

template<
    typename Policy1,
    typename Policy2,
    typename Policy3
>
class mutex_type
    : public Policy1
    , public Policy2
    , public Policy3
{
public:

    mutex_type();
    ~mutex_type();

protected:

    void do_unlock();
    void do_lock(cv_state& state);
    void do_unlock(cv_state& state);
};

class blocking_mutex_policy
{
protected:

    void do_lock();
};

class try_mutex_policy
{
protected:

    bool do_trylock();
};

//Always available but may be inefficient:
class timed_mutex_policy
{
protected:

    bool do_timedlock(const xtime& xt);
};

//Only available with platform support:
class fast_timed_mutex_policy
{
protected:

    bool do_timedlock(const xtime& xt);
};

//Example typedefs:

typedef mutex_type<
    blocking_mutex_policy,
    try_mutex_policy,
    fast_timed_mutex_policy
>
    mutex;

typedef blocking_mutex_type<
    blocking_mutex_policy,
    null_policy,
    null_policy
>
    mutex;

typedef try_mutex_type<
    try_mutex_policy,
    null_policy,
    null_policy,
>
    mutex;

typedef timed_mutex_type<
    timed_mutex_policy,
    null_policy,
    null_policy,
>
    mutex;

//---------- Lock ----------//

template<
    typename Mutex,
    typename Policy1,
    typename Policy2,
    typename Policy3
>
class lock_type
    : public Policy1
    , public Policy2
    , public Policy3
{
public:

    lock_type(Mutex& m, bool initially_locked = true);
    ~lock_type();

    void unlock();
    bool locked();
    operator const void*() const;

protected:

    void do_lock(cv_state& state);
    void do_unlock(cv_state& state);
};

class blocking_lock_policy
{
protected:

    void lock();
};

class try_lock_policy
{
protected:

    void try_lock();
};

class timed_lock_policy
{
protected:

    void timed_lock();
};

//Example typedefs:

typedef lock_type<
    blocking_lock_policy,
    try_lock_policy,
    timed_lock_policy
>
    lock;

typedef lock_type<
    blocking_lock_policy,
    null_policy,
    null_policy
>
    blocking_lock;

typedef lock_type<
    try_lock_policy,
    null_policy,
    null_policy>
    try_lock;

typedef lock_type<
    timed_lock_policy,
    null_policy,
    null_policy
>
    timed_lock;


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