unit PhiThread;

interface

uses
  Classes, Rubies;

type
  TPhiThread = class(TThread)
  private
    This: Tvalue;
    FSyncProc: Tvalue;
    procedure do_Sync;
    procedure do_Execution;
    procedure do_Exception;
  protected
    procedure Execute; override;
  public
    procedure Sync;
    procedure set_this(v: Tvalue);
    function alive_p: Boolean;
  published
    property SyncProc: Tvalue read FSyncProc write FSyncProc;
  end;

implementation

uses
{$IFDEF PHIEMBED}
  PhiMainUnit;
{$ELSE}
  Pythia;
{$ENDIF}

{ TPhiThread }

procedure TPhiThread.do_Sync;
begin
  ReturnValue := rb_funcall2(FSyncProc, rb_intern('call'), 0, nil);
end;

procedure TPhiThread.do_Execution;
begin
  ReturnValue := rb_funcall2(This, rb_intern('on_execute'), 0, nil);
end;

procedure TPhiThread.do_Exception;
begin

end;

function TPhiThread.alive_p: Boolean;
begin
  result := not Terminated;
end;

procedure TPhiThread.Sync;
begin
  try
    Synchronize(do_Sync);
  except
    Synchronize(do_Exception);
  end;
end;

procedure TPhiThread.Execute;
begin
  try
  try
    do_Execution;
  except
    Synchronize(do_Exception);
  end;
  finally
    Terminate;
  end;
end;

procedure TPhiThread.set_this(v: Tvalue);
begin
  This := v;
end;

end.
