Wednesday, February 10, 2021

Readers-writer lock - Part 4: Improving TLightweightMREW

While the TLightweightMREW is quite handy, it is not perfect. There's a weird assymmetry in it. On all operating systems that Delphi can compile for, read locks are reentrant (recursive) while write locks are not. In other words, if a thread already owns a read lock, it can call BeginRead again and it will succeed. Write locks are different. If a thread already owns a write lock and calls BeginWrite again, it will either deadlock (on Windows) or raise an exception (on other supported platforms).

This is, however, relatively simple to fix. I have implemented a simple wrapper for the TLightweightMREW lock in TLightweightMREWEx. This new record uses internal TLightweightMREW to provide locking and adds some simple logic to implement write lock reentrancy. The implementation and accompanying test program rwReentrantWriter can be found at

Monday, February 08, 2021

Readers-writer lock - Part 3: Some numbers

In order to convince you that a readers-writer lock is not a stupid idea, I should finally show some numbers. In this article I'll present a minimalistic (but still real-life) example which allows us to compare different locking solutions.

All code from this article is available in project rwLock at