首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >多个TThread实例

多个TThread实例
EN

Stack Overflow用户
提问于 2013-05-17 23:25:12
回答 1查看 561关注 0票数 1

我有一个TThread类,它可以独立运行,并在完成后终止和释放自己。我考虑过终止协议一切正常。问题是,我想添加一个特性,用户可以选择并选择同时活动多少个同步线程。一个例子是:

  • 程序必须完成100项总任务!
  • 用户选择3个线程应该同时运行,以完成所有任务。

我做的第一步是创建我的TThread类的3个实例,并在一个for循环中恢复它们。所以有3个线程在运行。在完成(或终止)第一个线程后,需要创建并恢复另一个新实例。

我被困在这一点上,我想知道我怎么能意识到这一点。任何建议都会有帮助。

编辑:一些代码

代码语言:javascript
复制
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

type
  TMyThread = class (TThread)
  public
  procedure Execute; override;
end;

var
  Form1       : TForm1;
  Threads     : Integer = 3;
  TotalTasks  : Integer = 100;

implementation

{$R *.dfm}

procedure TMyThread.Execute;
begin
  // some work...
  sleep (2000 + random (5000));
end;

function DummyThread ( p : pointer ) : Integer; stdcall;
var
  NewInstanceOfTMyThread  : TMyThread;
  I                       : Integer;
begin
  for I := 1 to Threads do begin
    with TMyThread.Create (TRUE) do begin
      resume;
    end;
  end;
  // Here should be code to detect if a new thread has to be started, etc.
end;

// We start the task to start the tasks...
procedure TForm1.Button1Click(Sender: TObject);
var
  ThreadID    : DWORD;
begin
  CloseHandle (CreateThread(NIL, 0, @DummyThread, NIL, 0, ThreadID));
end;

end.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-05-17 23:29:59

您可以为OnTerminate事件TThread编写一个处理程序。处理程序应该启动/恢复一个新线程。

或者,您可以有3个线程不断地运行,并从某个队列中接受任务(只需负责队列访问的同步)。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16619208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档