unit Main;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ExtCtrls,
  UWatek;

type
  TMainForm = class(TForm)
    Memo1: TMemo;
    Panel4: TPanel;
    btnSTART: TBitBtn;
    Panel1: TPanel;
    Panel2: TPanel;
    Panel3: TPanel;
    procedure btnSTARTClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
  private

  public
    MySemaphore  : Cardinal;
	 ilosc_watkow : Integer;

public
	 procedure  MyOnTerminate(Sender : TObject);
    procedure  Uruchom_watki();
  end;

var
  MainForm: TMainForm;

implementation
{$R *.dfm}
{------------------------------------------------------------------------------}
procedure TMainForm.btnSTARTClick(Sender: TObject);
begin
	if btnSTART.Caption = '&Start' then
	begin
		btnSTART.Caption := '&Koniec';
		btnSTART.Visible := false;

		Uruchom_watki();
	end
	else begin
		Application.Terminate();
	end;
end;

procedure TMainForm.FormShow(Sender: TObject);
begin
   Memo1.Clear();
   Memo1.Align := alLeft;
end;

procedure TMainForm.MyOnTerminate(Sender: TObject);
begin
	(*
	ten fragment się wykona gdy wątek zakończy sie
	w sposób 'naturany'
	*)

	Dec(ilosc_watkow);

	Memo1.Lines.Add('Ilość aktywnych wątków: ' + IntToStr(ilosc_watkow));

	if ilosc_watkow  = 0 then
	begin
		CloseHandle(MySemaphore);
		btnSTART.Visible := true;
	end;
end;

procedure TMainForm.Uruchom_watki();
var
   ob1, ob2, ob3       : MWatek;

	(*
	typedef struct _SECURITY_ATTRIBUTES
   {
   DWORD nLength;
   LPVOID lpSecurityDescriptor;
   BOOL bInheritHandle;
	} SECURITY_ATTRIBUTES
   *)
	SemaphoreAttributes : SECURITY_ATTRIBUTES;

begin
	Memo1.Clear();

	ilosc_watkow := 0;

   SemaphoreAttributes.nLength              := sizeof(SECURITY_ATTRIBUTES);
   SemaphoreAttributes.lpSecurityDescriptor := Nil;
   SemaphoreAttributes.bInheritHandle       := true;

	MySemaphore := CreateSemaphore(@SemaphoreAttributes, 3, 3, 'MW_SEMAFOR');

	// wątki:
	ob1 := MWatek.Create(true, Memo1, Panel1, 1, MySemaphore);
	ob1.OnTerminate := MyOnTerminate;
	Inc(ilosc_watkow);

	ob2 := MWatek.Create(true, Memo1, Panel2, 2, MySemaphore);
	ob2.OnTerminate := MyOnTerminate;
	Inc(ilosc_watkow);

	ob3 := MWatek.Create(true, Memo1, Panel3, 3, MySemaphore);
	ob3.OnTerminate := MyOnTerminate;
	Inc(ilosc_watkow);

	Memo1.Lines.Add('Ilość aktywnych wątków: ' + IntToStr(ilosc_watkow));

	ob1.Resume();
	ob2.Resume();
	ob3.Resume();
end;

end.
