
Antony, Thanks for the answer. This also answers the follow-up questions I had for Steven and Zeljko. Thanks and regards, Roland Anthony Williams wrote:
Roland Bock
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