Boost logo

Threads-Devel :

Subject: Re: [Threads-devel] a bad way to synchronize?
From: Anthony Williams (anthony_at_[hidden])
Date: 2011-01-24 06:42:47


On 23/01/11 21:29, nico wrote:
> I use boost::mutex in a strange way: lock in a thread, unlocked in another.
> It works for me, but is this behavior undefined and it works by luck?
> (by lock ;-) )

Yes, this will lead to undefined behaviour. If you want to do that then
you need a semaphore. Boost doesn't provide semaphores (though you can
build one with a flag, a mutex and a condition variable), but your
native OS API might.

> Here follows a quick explanation an code snippet to illustrate:
>
> * I lock a mutex in a thread.
> * I call the asynchronous function, passing a callback
> * I try to lock again the mutex: the thread that has just called the
> function is blocked

This is not guaranteed either: recursive locking of a non-recursive
mutex is undefined behaviour and may or may not do what you expect (in
common scenarios it will block or acquire the mutex a second time, as a
recursive mutex would, but these are not the only options).

> * The asynchronous function completes, calling the callback in
> another thread.
> * the mutex is unlocked in this thread and callback
> * the calling thread unblocks
> * et voila..

That sounds like an ideal case for boost::unique_future, actually: you
create a promise and then call your asynchronous function with a
callback. The calling thread then gets the future from the promise and
waits on it. When the async function is done it calls the callback,
which sets the promise, and wakes the waiting thread.

> Is this practice bad?

Yes.

> Should I prefer a mechanism based on boost::condition_variable?

Yes.

> I prefered the way I did, because it relies only on a mutex. With a
> condition_variable, their would be a little more stuff (a bool for
> completion, a mutex to protect it, and the condition_variable

True, but it will also work properly.

> In fact I have 2 particular questions:
>
> 1. 2 consecutive locks on the same mutex on the same thread: is it
> undefined behavior? It seems yes when boost 1.32, but no today
> (boost 1.44 - 1.45)

Yes.

> 2. Even if it is "again the nature of a mutex", is it bad to lock in
> a thread, and unlock in another, if like here, I'm sure there is
> no concurrent access t the mutex?

Yes. Depending on the mutex implementation it might not actually work.

Anthony

-- 
Author of C++ Concurrency in Action     http://www.stdthread.co.uk/book/
just::thread C++0x thread library             http://www.stdthread.co.uk
Just Software Solutions Ltd       http://www.justsoftwaresolutions.co.uk
15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK. Company No. 5478976

Threads-Devel list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk