Boost logo

Boost :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-01-31 15:41:59


From: "bill_kempf" <williamkempf_at_[hidden]>
> I think you misunderstand me here. A lock_ptr<> is not a thread safe
> shared_ptr<>, it's a completely new smart pointer that uses a proxy
> class to lock a mutex before accessing the object through operator->
> and unlock the mutex afterwards. It's an idea presented by Bjarne
> Stroustrup, and it's very difficult to implement using only a Scoped
> Lock.

A scoped lock works fine:

#include <boost/shared_ptr.hpp>
#include <iostream>

class mutex
{
public:

    class scoped_lock;

private:

    mutex(mutex const &);
    mutex & operator=(mutex const &);

    friend class scoped_lock;

    void lock()
    {
        std::cout << "mutex::lock\n";
    }

    void unlock()
    {
        std::cout << "mutex::unlock\n";
    }

public:

    mutex()
    {
    }

    class scoped_lock
    {
    public:

        explicit scoped_lock(mutex & m): m_(m)
        {
            m_.lock();
        }

        ~scoped_lock()
        {
            m_.unlock();
        }

    private:

        mutex & m_;

        scoped_lock(scoped_lock const &);
        scoped_lock & operator=(scoped_lock const &);
    };
};

class lock_ptr_proxy;

class object
{
private:

    friend class lock_ptr_proxy;
    mutable mutex m_;

public:

    void f()
    {
        std::cout << "object::f()\n";
    }
};

class lock_ptr_proxy
{
public:

    explicit lock_ptr_proxy(object * po): po_(po), pl_(new
mutex::scoped_lock(po->m_))
    {
    }

    object * operator->() const
    {
        return po_;
    }

private:

    object * po_;
    boost::shared_ptr<mutex::scoped_lock> pl_;
};

class lock_ptr
{
public:

    explicit lock_ptr(object & po): po_(&po)
    {
    }

    lock_ptr_proxy operator->() const
    {
        return lock_ptr_proxy(po_);
    }

private:

    object * po_;
};

int main()
{
    object o;

    lock_ptr lp(o);

    lp->f();
    lp->f();

    return 0;
}


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