Synchronization for multiple readers, single writer?

◇◆丶佛笑我妖孽 提交于 2019-11-30 10:04:11

There is a class for that purpose in RTL(sysutils) : TMultiReadExclusiveWriteSynchroniser

It is very easy to use. You don't need to strictly categorize your threads like reader or writer. Just call "BeginRead" or "BeginWrite" in a thread for starting a thread safe operation. Call "EndRead" or "EndWrite" for finishing the operation.

What you're looking for (and what vartec described) is called Reader(s)-Writer-Lock.

You can find some detailed notes on solving this problem at msdn magazine and an excerpt from Programming applications for MS windows.

Using a Reader-Writer lock will solve the problem. Multiple readers can access a database and a writer gets a lock once all readers are finished reading.

However, this might cause the writer to never have access to the source as there are always new readers who want access. This can be solved by blocking new readers when a writer wants access: the writer has a bigger priority. The writer gets access once all the readers on the source are done reading.

Whenever writer wants to access, you enqueue incoming readers (have them wait on Condition), wait for the active readers to finish, write and when finished let the enqueued readers access.

Nobody can really answer your question whether the serialization will affect performance in your application very much - you have to profile that for yourself, and the results will depend greatly on the number of threads, cores and the specific workload.

Note however that using more clever synchronization than critical sections, such as the reader-writer-lock, can introduce starvation problems that may be hard to debug and fix. You really need to look hard at whether the increased throughput outweighs the potential problems. Note also that there may not actually be an increase in throughput, especially if the locked code is very short and fast. There is a nice article by Jeffrey Richter that actually contains this quote:

Performance Even when there is no contention for a ReaderWriterLock, its performance is very slow. For example, a call to its AcquireReaderLock method takes about five times longer to execute than a call to Monitor's Enter method.

This is for .NET of course, but the underlying principles do apply as well.

The reader-writer lock is what you need. Tutorial has a description, but I'm sure someone was adding this as standard to Delphi. May be worth checking D2009 doesn't have it already.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!