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
    MyMutex      : Cardinal;	// uchwyt
    ilosc_watkow : Integer;
    my_thread1          : MWatek;
    my_thread2          : MWatek;
    my_thread3          : MWatek;

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

var
  MainForm: TMainForm;

implementation
{$R *.dfm}
{------------------------------------------------------------------------------}
procedure TMainForm.FormShow(Sender: TObject);
begin
   Memo1.Clear();
   Memo1.Align := alLeft;
end;

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.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(MyMutex);
		btnSTART.Visible := true;
   end;
end;

procedure TMainForm.Uruchom_watki();
begin
   Memo1.Clear();

   // przygotowujemy Mutex
   (*
	HANDLE CreateMutex
   (
   LPSECURITY_ATTRIBUTES lpMutexAttributes,
   BOOL bInitialOwner,
   LPCTSTR lpName
   );
   *)
   MyMutex := CreateMutex(Nil, false, 'MW_MUTEX');

   ilosc_watkow := 0;

   my_thread1 := MWatek.Create(true, Memo1, Panel1, 1, MyMutex);
   my_thread1.OnTerminate := MyOnTerminate;
   Inc(ilosc_watkow);

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

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

   my_thread1.Resume();
   my_thread2.Resume();
   my_thread3.Resume();
end;

end.

