Avoiding Simultaneous Thread Access to the Same Memory

From RAD Studio
Jump to: navigation, search

Go Up to How To Build Multithreaded Applications

Use these basic techniques to prevent other threads from accessing the same memory as your thread:

To lock objects

  1. For objects such as canvas that have a Lock method, call the Lock method, as necessary, to prevent other objects from accessing the object, and call Unlock when locking is no longer required.
  2. Call TThreadList.LockList (Delphi) or TThreadList::LockList() (C++) to block threads from using the list object TThreadList, and call TThreadList.UnlockList when locking is no longer required.

Note: You can safely make calls to TCanvas.Lock and TThreadList.LockList.

To use a critical section

  1. Create a global instance of TCriticalSection.
  2. Call the Acquire method to lock out other threads while accessing global memory.
  3. Call the Release method so other threads can access the memory by calling Acquire. The following code has a global critical section variable LockXY that blocks access to the global variables X and Y. To use X or Y, a thread must surround that use with calls to the critical section such as shown here:

Delphi:

LockXY.Acquire;
try
  X := X + 1;
  Y := sin(X);
finally
  LockXY.Release
end;

C++:

LockXY->Acquire();
try
{
  x++;
  y = sin( x );
}
__finally
{
  LockXY->Release();
}

Warning: Critical sections only work if every thread uses them to access global memory. Otherwise, problems of simultaneous access can occur.

To use the multi-read exclusive-write synchronizer

  1. Create a global instance of TMultiReadExclusiveWriteSynchronizer that is associated with the global memory you want to protect.
  2. Before any thread reads from the memory, it must call BeginRead.
  3. At the completion of reading memory, the thread must call EndRead.
  4. Before any thread writes to the memory, it must call BeginWrite.
  5. At the completion of writing to the memory, the thread must call EndWrite.

Warning: The multi-read exclusive-write synchronizer only works if every thread uses it to access the associated global memory. Otherwise, problems of simultaneous access can occur.

See Also