Subject: Re: [Threads-devel] an obscurity in void basic_timed_mutex::clear_waiting_and_try_lock(long& old_count)
From: Anthony Williams (anthony_at_[hidden])
Date: 2013-02-12 03:22:21
On 11/02/13 11:13, Stefan Djukic wrote:
> So, I cannot understand what is the point of using the old_count as the
> input value in void basic_timed_mutex::clear_waiting_and_try_lock(long&
> old_count). At that point, the /old_count in all threads waiting on
> mutex would be less than the current value of active_count/ (the way it
> is done in mark_waiting_and_try_lock()).
Not necessarily. If there are multiple competing mutexes, then the
old_count may be wrong for the first call to clear_waiting_and_try_lock,
but correct for a subsequent call (if this thread failed to get the lock).
> In the first iteration of clear_waiting_and_try_lock() the value of the
> old_count will always be compared to active_count, and after that, as it
> would be different, use its current value for the next iteration. So,
> what's the point of the first iteration? On the other hand, it seems
> planned very carefully to do exactly that, but I cannot see why. Why not
> instead of the line old_count&=~lock_flag_value; set the old_count to
> zero, or even better to: old_count=active_count&~lock_flag_value;, that
> way, at least, one thread could obtain the lock in the first iteration.
> It also seems, that the first versions of mutex (prior to rev 45119),
> would not have this first extra iteration.
> Anyway, I do not see much harm in the way it's done, but not much
> benefit, either.
The intent is to avoid an extra load from active_count. Looking at the
code fresh, it is clear that it will behave as you describe in at least
some scenarios, which does rather make the issue moot.
I think a better solution is to ensure that old_count is correct before
the loop that calls clear_waiting_and_try_lock, so if there is no change
then the compare_exchange will work first time.
I've checked in a patch on trunk that does just that (rev 82828).
-- Author of C++ Concurrency in Action http://www.stdthread.co.uk/book/ just::thread C++11 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