Boost logo

Boost :

Subject: Re: [boost] [thread] Moving a `recursive_lock`
From: Andrey Semashev (andrey.semashev_at_[hidden])
Date: 2010-02-14 05:32:45

On 02/14/2010 05:50 AM, Daniel Trebbien wrote:
> Hello all,
> 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`.
> After writing some test code, I find it interesting that if I use a
> `recursive_mutex`, then an assertion fails, but if I use a
> `boost::mutex`, then the code seems to work fine.
> Here is the test code that I have been experimenting with (the
> `recursive_mutex` version, which is also attached):
> This leads me to wondering:
> 1. Is it correct and/or safe to move a lock to a new thread in this way?
> 2. Why does the `recursive_mutex` version fail and the `mutex` version
> succeed?

AFAIK, locking a mutex in one thread and unlocking it in the other leads
to undefined behavior. See here:

   void unlock()

       The current thread owns *this.

Also, as Boost.Thread is modeled closely after pthreads, and what you're
trying to do is also considered as error there:

Boost list run by bdawes at, gregod at, cpdaniel at, john at