TCriticalSection with many readers and one writer

Viewed 179

I have a service app written in Delphi 10 Seattle Win32 which has in-memory data that is updated regularly in a thread.

As the data is a complex structure and received in chunks, the update code writes to a temporary list and when it completes the structure switches this temporary list to a "production" list which is read by many reader threads.

I sat the "switch" code as a critical section along with the respective readers to have them mutually excluded. I realized later that as a side effect the reader threads are mutually exclusive among them too.

My question is if there is an alternative critical section class that I can characterize as reader o writer so as to allow readers to execute simultaneously.

Besides this, I protected only the reader code which gathers the data it has to send and makes copies of this data to be send after leaving the critical section. I wonder whether it should be more performant to have this data gathering code mutually exclusive anyway or serialized.

Thanks in advance.

1 Answers

There is TMultiReadExclusiveWriteSynchronizer in SysUtils. (If you like your fingers, consider using the TMREWSync alias from the same unit.)

Keep in mind, though, that it is terribly slow and that many times a simple critical section will perform better.

As you are compiling for Windows, you may also consider using Slim Reader/Writer. That one is Windows-specific, but extremely fast.

Related