Walter is right about transitive readonly - here's the alternative
Sean Kelly
sean at f4.ca
Thu Sep 13 13:25:39 PDT 2007
Janice Caron wrote:
> On 9/13/07, Steven Schveighoffer <schveiguy at yahoo.com> wrote:
>> Without remembering which threads have read locks, you can just use a simple
>> reference counter to tell if a object is read-locked.
>
> My C++ implementation used an atomic counter for read locks, an atomic
> counter for (pending) write locks, and an OS mutex.
For comparison, my D implementation uses a mutex and two condition
variables. The condvars simplify blocking when a write lock is held, etc.
>> When "upgrading" becomes possible, then you have to know whether the thread
>> you are in holds a read-lock or not. This means you have to store (probably
>> in the mutex itself) a list of all threads that hold the read-lock. Then
>> when you go to do the upgrade, it must check to see if the upgrading thread
>> is in the list. This is at least a O(lg(n)) operation, whereas a reference
>> counter is a O(1).
...
> Upgrading just isn't possible in any case - not even in /theory/, let
> alone in a given implementation.
I'm sure it could be done (in fact, POSIX has this feature), but the
implementation would be a mess and provide marginal gain.
>> and write locks could be reentrant (only
>> have to store one thread id, you could even use the same reference counter
>> as the read locks).
>
> My implementation wasn't re-entrant for write locks. I never found it
> necessary. That said, I know that it is possible to make re-entrant
> write locks, but probably not by the means that you suggest.
It's possible but to do so I think you'd have to maintain a list of
which threads held which lock. This doesn't seem terribly efficient,
and just not worthwhile for something that is of marginal utility.
>> So the only really "bad" situation is:
>>
>> readable(o);
>> writable(o);
>
> You cannot get a write lock if you already have a read lock on the
> same object. It is impossible. That is a deadlock.
Or a read lock if you already have a write lock on something. Doing so
would be kind of pointless anyway, and therefore I'd consider it a
programming error to do so.
Sean
More information about the Digitalmars-d
mailing list