views:

192

answers:

3

How can I achieve a synchronization structure like that:

Lock.BeginRead
try
  if Changed then
    begin
    Lock.BeginWrite;
    try
      Update;
    finally
      Lock.EndWrite;
    end;
    // ... do some other stuff ...
    end;
finally
  Lock.EndRead;
end;

without loosing the read lock after the EndWrite, so that no other writers can execute while this code block is executed.

How does Delphi 2009's TMuliReadExclusiveWriteSynchronizer behave in this case?

+1  A: 

First: Your code from EndWrite resides in TSimpleRWSync, which is a lightweight implementation of IReadWriteSync, while TMultiReadExclusiveWriteSynchronizer is much more sophisticated.

Second: The call to LeaveCriticalSection(FLock) in EndWrite doesn't release the lock if there are still some open calls to EnterCriticalSection(FLock) (like the one in BeginRead).

This means your code example is quite valid and should work as expected wether you are using a TSimpleRWSync instance or a TMultiReadExclusiveWriteSynchronizer instance.

Uwe Raabe
+1 Thanks! That's very good news for me. I did lookup the wrong implementation - just did a text search for EndWrite. Sorry about that
Smasher
+1  A: 

I don't have Delphi 2009 but I expect there were no changes in the way TMultiReadExclusiveWriteSynchronizer works. I think it is the right structure to use for your scenario with one remark: the "BeginWrite" is a function returning a Boolean. Make sure you check its result before doing the write operations.

Also, in Delphi 2006 the TMultiReadExclusiveWriteSynchronizer class has a lot of developer comments in it and also some debug code. Make sure you take a look at the implementation before using it.

See also: Working with TMultiReadExclusiveWriteSynchronizer on EDN

Tihauan
A: 

Thanks to the answers of Uwe Raabe and Tihauan:

TMultiReadExclusiveWriteSynchronizer works fine with such nested locking structures. The EndWrite does not realease the read lock, so it is easily possible to promoto a read-lock to a write-lock for a certain period of time and then to return to the read-lock without other writers interfering.

Smasher