Boost logo

Boost :

Subject: Re: [boost] [thread] Moving a `recursive_lock`
From: Seth Bunce (seth_at_[hidden])
Date: 2010-02-14 05:31:16


On Sat, 2010-02-13 at 18:50 -0800, Daniel Trebbien wrote:
> I have been working on a project that uses the Boost Thread library, and I
> realized that there is a part of the code that needs to transfer a lock to
> a thread that has just been started. My idea for implementing this was to
> use a `boost::recursive_mutex` and pass a non-`const` reference to a
> `boost::recursive_mutex::scoped_lock` to the thread via `boost::ref`.
> Also, to ensure that the `scoped_lock` does not go out of scope until
> until the lock is moved, I thought to use a `boost::barrier`.

Would a boost::shared_ptr<boost::mutex> work in this situation? If you
used a shared_ptr you wouldn't have to worry about when stuff goes out
of scope. You could also use a thread join to wait for the thread to die
instead of a barrier.

I'm thinking of something like this. In my view this approach is more
strait forward. However, I don't know if it meets your requirements.

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

void f(boost::shared_ptr<boost::mutex> M)
{
        boost::mutex::scoped_lock lock(*M);
        std::cout << "do stuff\n";
}

int main()
{
        boost::shared_ptr<boost::mutex> M(new boost::mutex());
        boost::thread T;
        {//BEGIN lock scope
        boost::mutex::scoped_lock lock(*M);
        T = boost::thread(&f, M);
        }//END lock scope
        T.join();
        std::cout << "finish\n";
}


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