On 14/05/2013 07.46, Vicente J. Botet Escriba wrote:
Le 14/05/13 00:44, Gaetano Mendola a écrit :
Unlocking as soon as possible is something it should happen whenever is possible, but basically you are doing this kind of optimization:
instead of
void foo() { boost::unique_lockboost::mutex lk(mutex_); .... return; }
you are optimizing doing this:
void foo() { boost::unique_lockboost::mutex lk(mutex_); ... lk.unlock; return; }
and I'm asking, is it worth? Do you have an evidence of it ? Having say that do whatever you believe is better in terms of clarity and correctness. I have seen also that in a couple of points the unique_lock can be replaced by a lock_guard (and possibly declared const).
Sorry Gaetano,
I have an uncommitted version where
bool count_down(unique_lock<mutex> &lk) /// pre_condition (count_.value_ > 0) { BOOST_ASSERT(count_.value_ > 0); if (--count_.value_ == 0) { lk.unlock(); count_.cond_.notify_all(); // unlocked !!! return true; } return false; }
Maybe I'm wrong and I'm doing premature optimization and it is better to use lock_guard and don't unlock before notifying. As you point it is in any case clearer.
Now it makes sense, unlocking prematurely an unique lock without the use of an extra scope is something not natural, it is at least a weird pattern, I believe the source of the "problem" is in the implementation of that boost::detail::counter indeed as you can see it has a counter and a condition and users of it are obliged to protect both counter and condition (even if not needed) look at inc_and_notify_all for example.
Measures would be needed :(
Not worth to measure it, I asked that because I saw an unusual "optimization" and it was interesting to know if you did that due your past experience with it. Regard Gaetano Mendola