Walter is right about transitive readonly - here's the alternative

Bruce Adams tortoise_74 at yeah.whoo.co.uk
Thu Sep 13 16:09:22 PDT 2007


Sean Kelly Wrote:

> Janice Caron wrote:
> > On 9/13/07, Sean Kelly <sean at f4.ca> wrote:
> >>> 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
> > 
> > It certainly can't be done atomically...
> > 
> > Threads 1 and 2 both successfully obtain a read lock.
> > Thread 1 attempts to upgrade to a write lock. Since thread 2 has a
> > read lock, it waits.
> > Thread 2 attempts to upgrade to a write lock. Since thread 1 has a
> > read lock, it waits.
> > Deadlock.
> > 
> > 
> >> (in fact, POSIX has this feature)
> > 
> > I wonder how. If it's implemented as release the read lock followed by
> > obtain a write lock, then the caller must beware that another thread
> > may have written /during/ the upgrade.
> 
> If I had to guess, I'd say that the upgrade works by ensuring that 
> upgrading readers are given precedence when acquiring a write lock, so 
> there is no risk of an external writer acquiring the lock if there are 
> any readers in the process of upgrading.  Since the POSIX library is 
> already explicitly managing the list of waiters rather than relying on 
> someone else's mutex/condvar/semaphore/whatever to do so, the additional 
> logic may not be a terrible burden.
> 
> 
> Sean

Posix provides this feature for advisory FILE lockiing and not for looking areas of memory though there is some parallel (especially if you use memory mapped files). These locks are per process and mediated by the OS rather than per thread. The fcntl call can fail or the process can be told to wait forever, inviting deadlock. The POSIX API is very low level and typically needs to be wrapped up to make it more user friendly.
 
The POSIX threads API is similarly low level but with looser semantics.
It supports several types of lcok:
   normal locks
  recursive locks (where you can relock a mutex you own and must unlock it the same number of times before it is unlocked).
 error checked locks (unlocking a mutex you don't have locked or relocking one you do is reported as an error).

I don't think going POSIX is the answer in this case.

However, I do believe the ability to try a lock or specify a timeout is important. Janice's solution though elegant does not provide support for this. At minimum a "trylock / islock" is required on which the rest can be built.

I agree with Bill that support for thread-safety should be implemented as a library. Ideally part of the standard library. I think we're back to redecorating the christmas tree here.

Regards,

Bruce.





More information about the Digitalmars-d mailing list