The Thread Class in Delphi (2)

Source: Internet
Author: User
Tags constructor thread class

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.