Sunday, November 08, 2020

Readers-writer lock - Part 1: Why?

One of the pleasant surprises in Delphi 10.4.1 was the addition of a new readers-writer lock implementation TLightweightMREW. While it was probably not noticed by most of the users, I was quite happy to see it implemented. 

So now you are asking yourself - what is this readers-writer lock and why am I so happy to see it in Delphi? Well, I'm glad that you're asking! Let me explain ...

In multithreaded programming (as most of my horror stories start), we frequently run into a problem of resource sharing. Two threads want to modify a shared resource at the same time and that can cause many problems, from information being overwritten to corrupted data and program crashes.

To fix this, we add resource protection. Usually that is just a critical section (typically through a TCriticalSection wrapper), or Delphi's TMonitor. Sometimes, however, protecting resources with a simple critical section causes an unnecessary performance drop, and that's when a readers-writer lock (may) come into play.