Use these basic techniques to prevent other threads from accessing the same memory as your thread:
- Lock objects.
- Use critical sections.
- Use a multi-read exclusive-write synchronizer
To lock objects
- 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.
- 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
- Create a global instance of TCriticalSection.
- Call the Acquire method to lock out other threads while accessing global memory.
- 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:
LockXY.Acquire;
try
X := X + 1;
Y := sin(X);
finally
LockXY.Release
end;
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
- Create a global instance of TMultiReadExclusiveWriteSynchronizer that is associated with the global memory you want to protect.
- Before any thread reads from the memory, it must call BeginRead.
- At the completion of reading memory, the thread must call EndRead.
- Before any thread writes to the memory, it must call BeginWrite.
- 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.