I have a TThread Class that can run independently and terminates and frees itself after it's done. I considered the termination and everything works. The problem is, that I would like to add a feature that the user can select and choose how many SYNCHRONOUS threads should be active at the same time. An example would be:
- The program has to do 100 total tasks!
- The user chooses 3 Threads should be running at the same time to complete all the tasks.
The first step I did was to create 3 instances of my TThread Class and the resume them in a for loop. So 3 threads are running. After the first thread is done (or terminated), another new instance needs to be created and resumed.
I get stuck on this point and I wonder how I can realize this. Any advice would be helpful.
Edit: Some Code
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.