Boost logo

Boost Users :

Subject: Re: [Boost-users] [Thread] order of shared_lock and unique_lock acquisitions
From: Anthony Williams (anthony.ajw_at_[hidden])
Date: 2009-01-09 09:17:27


Roland Bock <rbock_at_[hidden]> writes:

> Hi,
>
> I am trying to use shared_lock and unique_lock on a shared_mutex to
> allow read-functions to access a certain resource in parallel, but
> write functions use the resource exclusively.
>
> Is there a way to determine the order in which the (shared) locks are
> acquired? I tried testing with the attached program and got rather
> weird and (seemingly) non-deterministic results.
>
> In the test program (see attachment), I start 9 threads of readers(r)
> and writers(w). Before doing anything else, the sleep and wake up in
> groups.
>
> rrww
> rr
> w
> rr
>
> There is one second delay between the groups I would expect to see
> them working in this order:
>
> rr
> w
> w
>
> rr
>
> w
>
> rr
>
> The first group could be scrambled of course since they race for the
> lock. But at least I would expect the order of groups to be
> maintained.
>
> I get quite different results, though, and the results differ from run
> to run. The weirdest result I saw until now is attached.
>
> rr
>
> rrr (these do not start before the first group is finished)
>
> w
> w
> w (the last writer is handled in second position btw)
>
> r
>
> This I do not understand at all. The readers are using the shared
> mutex. Why is the second group waiting for the first to be finished?
> And how can the last writer be handled in second place?

The implementation detects that there are waiting writers, and so
prevents further shared locks being acquired. Once all the existing
shared locks are released, then all currently-waiting threads compete
for the lock. In this case, three readers got in before the writers
woke.

The lock acquisition is not FIFO. The OS decides which of the waiting
threads acquires the lock next.

Anthony

-- 
Anthony Williams
Author of C++ Concurrency in Action | http://www.manning.com/williams
Custom Software Development | http://www.justsoftwaresolutions.co.uk
Just Software Solutions Ltd, Registered in England, Company Number 5478976.
Registered Office: 15 Carrallack Mews, St Just, Cornwall, TR19 7UL, UK

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net