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 FormShow(Sender: TObject);
    procedure btnSTARTClick(Sender: TObject);

  private
    MySemaphore  : Cardinal;	// uchwyt do semafora
    ilosc_watkow : Integer;

	 procedure MyOnTerminate(Sender : TObject);

  public
	 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
	my_thread1 : MWatek;
	my_thread2 : MWatek;
	my_thread3 : MWatek;

begin
   Memo1.Clear();

   ilosc_watkow := 0;

   // przygotowujemy semafor
   (*
   HANDLE CreateSemaphore
   (
   LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,	// pointer to security attributes
   LONG lInitialCount,	// initial count
   LONG lMaximumCount,	// maximum count
   LPCTSTR lpName 	// pointer to semaphore-object name
   );
   *)
   MySemaphore := CreateSemaphore(Nil, 3, 3, 'MW_SEMAFOR');


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

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

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

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

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

end.

