The TRTLCriticalSection type is an Opaque type; it depends on the OS on which the code is executed. It should be initialized before it is rst used, and should be disposed of when it is no longer necessary.
To protect a piece of code, a call to EnterCriticalSection should be made: When this call returns, it is guaranteed that the current thread is the only thread executing the subsequent code. The call may have suspended the current thread for an inde nite time to ensure this.
When the protected code is nished, LeaveCriticalSection must be called: this will enable other threads to start executing the protected code. To minimize waiting time for the threads, it is important to keep the protected block as small as possible.
The de nition of these calls is as follows:
procedure InitCriticalSection(var cs: TRTLCriticalSection);
procedure DoneCriticalSection(var cs: TRTLCriticalSection); procedure EnterCriticalSection(var cs: TRTLCriticalSection); procedure LeaveCriticalSection(var cs: TRTLCriticalSection); |
The meaning of these calls is again almost obvious:
Note that the LeaveCriticalsection call must be executed. Failing to do so will prevent all other threads from executing the code in the critical section. It is therefore good practice to enclose the critical section in a Try..finally block. Typically, the code will look as follows:
Var
MyCS : TRTLCriticalSection; Procedure CriticalProc; begin EnterCriticalSection(MyCS); Try // Protected Code Finally LeaveCriticalSection(MyCS); end; end; Procedure ThreadProcedure; begin // Code executed in threads... CriticalProc; // More Code executed in threads... end; begin InitCriticalSection(MyCS); // Code to start threads. DoneCriticalSection(MyCS); end. |