delphi Parallel의 Ttask 첫 번째 시도
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
System.Generics.Collections;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Memo2: TMemo;
Memo3: TMemo;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
System.Threading, System.SyncObjs, System.Diagnostics;
procedure TForm1.Button1Click(Sender: TObject);
const
C = 1000;
var
TaskArray: array of ITask;
I: Integer;
ATask: ITask;
begin
Button1.Enabled := False;
Memo1.Clear;
Memo2.Clear;
Memo3.Clear;
SetLength(TaskArray, C);
for I := 0 to C - 1 do
begin
TaskArray[I] := TTask.Create(procedure
var
Id: string;
begin
Id := TThread.Current.ThreadID.ToString;
TThread.Queue(nil, procedure
begin
if Memo1.Lines.IndexOf(Id)=-1 then
Memo1.Lines.Add(Id);
//Memo2.Lines.Add( IntToStr(Memo2.Lines.Count+1) );
end);
end);
TaskArray[I].Start;
end;
TThread.CreateAnonymousThread(procedure
var
I: Integer;
Task: ITask;
J: Integer;
begin
I := C;
while I > 0 do
begin
for Task in TaskArray do
if Task.Status = TTaskStatus.Completed then
Dec(I);
end;
TThread.Synchronize(nil, procedure
begin
Memo1.Lines.Add('OK');
Button1.Enabled := True;
end);
//
for J := 0 to C - 1 do
TaskArray[J] := nil;
end).Start;
if TTask.WaitForAll(TaskArray) then
Memo1.Lines.Add('WaitForAll');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
ReportMemoryLeaksOnShutdown := True;
end;
end.
결과 내보내기
1 WaitForAll
2 7120
3 7064
4 7052
5 OK
6 3272
때때로 출력 결과는 다음과 같습니다.
1 WaitForAll
2 7064
3 7120
4 3272
5 7052
6 OK
테스트 결과:
1 WaitForAll은 기본 스레드를 차단하지 않습니다.
2 100개의 TTASk는 100개의 라인을 만들지 않습니다. 코드를 쓰지 않아도 [라인 풀]과 같은 기능을 얻을 수 있습니다!
3 Task 가 모두 종료되었는지 확인할 수 없습니다??
4 라인에서 [인터페이스]가 관련되었을 때 주의해야 합니다!
테스트 환경:
win10 + delphi 10.1 berlin
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.