Using Critical Sections

From RAD Studio
Jump to: navigation, search

Go Up to Avoiding Simultaneous Access


If objects do not provide built-in locking, you can use a critical section. Critical sections work like gates that allow only a single thread to enter at a time. To use a critical section, create a global instance of System.SyncObjs.TCriticalSection. System.SyncObjs.TCriticalSection has two methods, Acquire (which blocks other threads from executing the section) and Release (which removes the block).

Each critical section is associated with the global memory you want to protect. Every thread that accesses that global memory should first use the Acquire method to ensure that no other thread is using it. When finished, threads call the Release method so that other threads can access the global memory by calling Acquire.

Warning: Critical sections only work if every thread uses them to access the associated global memory. Threads that ignore the critical section and access the global memory without calling Acquire can introduce problems of simultaneous access.

For example, consider an application that has a global critical section variable, LockXY, that blocks access to global variables X and Y. Any thread that uses X or Y must surround that use with calls to the critical section such as the following:

LockXY.Acquire; { lock out other threads }
try
  Y := sin(X);
finally
  LockXY.Release;
end;
pLockXY->Acquire(); // lock out other threads
try {
    Y = sin(X);
}
__finally {
    pLockXY->Release();
}

See Also