Synchronization for multiple readers, single writer?

后端 未结 7 527
余生分开走
余生分开走 2021-01-01 01:32

Another synchronization question...I hope you guys don\'t get annoyed ;)

Assume the following scenario: one central data structure (very large, so I don\'t really wa

相关标签:
7条回答
  • 2021-01-01 01:56

    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.

    0 讨论(0)
  • 2021-01-01 02:02

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

    0 讨论(0)
  • 2021-01-01 02:06

    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.

    0 讨论(0)
  • 2021-01-01 02:12

    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.

    0 讨论(0)
  • 2021-01-01 02:12

    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.

    0 讨论(0)
  • 2021-01-01 02:14

    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.

    0 讨论(0)
提交回复
热议问题