RAD Studio |  |

Using Critical Sections
See Also
Collapse All

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 TCriticalSection. 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:
Copy Code

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

Copy Code

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

See Also

Locking Objects

Using the Main VCL Thread

Using the Multi-read Exclusive-write Synchronizer

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!