Show: Delphi C++
Display Preferences

Using the Multi-read Exclusive-write Synchronizer

From RAD Studio
Jump to: navigation, search

Go Up to Coordinating threads Index

When you use critical sections to protect global memory, only one thread can use the memory at a time. This can be more protection than you need, especially if you have an object or variable that must be read often but to which you very seldom write. There is no danger in multiple threads reading the same memory simultaneously, as long as no thread is writing to it.

When you have some global memory that is read often, but to which threads occasionally write, you can protect it using System.SysUtils.TMultiReadExclusiveWriteSynchronizer. This object acts like a critical section, but allows multiple threads to read the memory it protects as long as no thread is writing to it. Threads must have exclusive access to write to memory protected by TMultiReadExclusiveWriteSynchronizer.

To use a multi-read exclusive-write synchronizer, create a global instance of TMultiReadExclusiveWriteSynchronizer that is associated with the global memory you want to protect. Every thread that reads from this memory must first call the BeginRead method. BeginRead ensures that no other thread is currently writing to the memory. When a thread finishes reading the protected memory, it calls the EndRead method. Any thread that writes to the protected memory must call BeginWrite first. BeginWrite ensures that no other thread is currently reading or writing to the memory. When a thread finishes writing to the protected memory, it calls the EndWrite method, so that threads waiting to read the memory can begin.

Warning: Like critical sections, the multi-read exclusive-write synchronizer only works if every thread uses it to access the associated global memory. Threads that ignore the synchronizer and access the global memory without calling BeginRead or BeginWrite introduce problems of simultaneous access.

See Also

Personal tools
In other languages