The first is the constructor:
constructor TThread.Create(CreateSuspended: Boolean);
begin
inherited Create;
AddThread;
FSuspended := CreateSuspended;
FCreateSuspended := CreateSuspended;
FHandle := BeginThread(nil, 0, @ThreadProc, Pointer(Self), CREATE_SUSPENDED, FThreadID);
if FHandle = 0 then
raise EThread.CreateResFmt(@SThreadCreateError, [SysErrorMessage(GetLastError)]);
end;
Although this constructor does not have much code, it can be considered one of the most important members, because the thread is created here.
After calling Tobject.create through inherited, the first sentence is to call a process: Addthread, its source code is as follows:
procedure AddThread;
begin
InterlockedIncrement(ThreadCount);
end;
There is also a corresponding removethread:
procedure RemoveThread;
begin
InterlockedDecrement(ThreadCount);
end;
Their function is simply to count the number of threads in the process by adding or subtracting a global variable. Only here is used to add and subtract variables are not commonly used inc/dec process, but with the interlockedincrement/interlockeddecrement of this pair of processes, they achieve the same function, are the variable plus one or minus one. But they have one of the biggest differences, that is, interlockedincrement/interlockeddecrement is thread-safe. That is, they can guarantee the execution result is correct under the multithreading, but Inc/dec cannot. Or in terms of operating system theory, this is a pair of "primitive" operations.
Take plus one as an example to illustrate the difference in the implementation details of the two:
In general, there are three steps after the operation of the memory data is decomposed:
1, read the data from the memory
2, Data plus a
3, Memory