我有一个TThread类,它可以独立运行,并在完成后终止和释放自己。我考虑过终止协议一切正常。问题是,我想添加一个特性,用户可以选择并选择同时活动多少个同步线程。一个例子是:
我做的第一步是创建我的TThread类的3个实例,并在一个for循环中恢复它们。所以有3个线程在运行。在完成(或终止)第一个线程后,需要创建并恢复另一个新实例。
我被困在这一点上,我想知道我怎么能意识到这一点。任何建议都会有帮助。
编辑:一些代码
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.发布于 2013-05-17 23:29:59
您可以为OnTerminate事件TThread编写一个处理程序。处理程序应该启动/恢复一个新线程。
或者,您可以有3个线程不断地运行,并从某个队列中接受任务(只需负责队列访问的同步)。
https://stackoverflow.com/questions/16619208
复制相似问题