Enter;
The Enter method enters a critical section.
After the Enter method is called, if class global variables are changed, access to them is locked until the Leave method call. If it is attempted to change the same variables from other thread, the work of this thread will be paused until the access to the variables is restored.
Executing the example requires that the repository contains a unit with the M_THREAD_CALC identifier. The specified classes and method are implemented in the unit.
Add a link to the Fore system assembly.
Class CCritSection: Object
Shared fcs: IForeCriticalSection;
Public Shared Property CritSection: IForeCriticalSection
Get
Begin
If IsNull(fcs) Then
fcs := New ForeCriticalSection.Create;
End If;
Return fcs;
End Get
End Property CritSection;
End Class CCritSection;
Class CCalculate: Object
Public Shared Res: Double;
Public Shared Error: String;
Public Shared Sub Run;
Var
Method: IForeMethod;
Th1, Th2: IForeThread;
Begin
Method := New ForeMethod.Create;
Method.Assembly := "M_THREAD_CALC";
Method.Method := "Calculate";
//Create threads
Th1 := New ForeThread.Create(Method);
Th1.Name := "A";
Th1.Start(Th1);
Th2 := New ForeThread.Create(Method);
Th2.Name := "B";
Th2.Start(Th2);
//...
//Continue main program with the ability to monitor thread state
//...
End Sub Run;
End Class CCalculate;
Sub Calculate(Th: Variant);
Begin
//...
//Operations to execute some calculation
//...
//Enter critical section
CCritSection.CritSection.Enter;
If (Th As IForeThread).Name = "A" Then
CCalculate.Res := 100;
CCalculate.Error := "A";
(Th As IForeThread).Sleep(1000);
Else
CCalculate.Res := 200;
CCalculate.Error := "B";
(Th As IForeThread).Sleep(2000);
End If;
//Exit critical section
CCritSection.CritSection.Leave;
End Sub Calculate;
The specified example on executing the Run static method of the CCalculate method displays creating two threads that execute the Calculate custom class. The method itself, depending on some conditions, can change static fields of the CCalculate class. To avoid the situation when two threads simultaneously change class fields, the critical section is used that is implemented by the CCritSection class.
See also: