unit Main;

interface

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

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

  private
	 // address of critical section object
    ilosc_watkow      : Integer;

    my_thread1        : MWatek;
    my_thread2        : MWatek;
    my_thread3        : MWatek;
    MyCriticalSection : RTL_CRITICAL_SECTION;

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

  public

  end;

var
  MainForm: TMainForm;

implementation
{$R *.dfm}
{------------------------------------------------------------------------------}
procedure TMainForm.btnSTARTClick(Sender: TObject);
begin
	Memo1.Clear();

	if btnSTART.Caption = '&Start' then
	begin
		btnSTART.Caption := '&Koniec';
		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);
	lblILOSC.Caption := IntToStr(ilosc_watkow);

	if ilosc_watkow =  0 then
	begin
		DeleteCriticalSection(&MyCriticalSection);
		ShowMessage('KONIEC');
   end;
end;

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

   ilosc_watkow := 0;
   InitializeCriticalSection(MyCriticalSection);

   // uruchamiamy trzy wątki na raz
   my_thread1 := MWatek.Create(true, Memo1, Panel1, 1, MyCriticalSection);
   my_thread1.OnTerminate := MyOnTerminate;
   Inc(ilosc_watkow);

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

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

   lblILOSC.Caption := IntToStr(ilosc_watkow);

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

end.

