I'm trying implement threads in my program.
I made a very simple test program, but it's not working (sometimes print numbers till 50 - 70, not 100, sometimes gives a segmentation fault). I think it's because program terminates before thread finishes it's work:
program test;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
cmem,
pthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp, MyThreads
{ you can add units after this };
type
{ TMyApplication }
TMyApplication = class(TCustomApplication)
protected
procedure DoRun; override;
public
end;
{ TMyApplication }
procedure TMyApplication.DoRun;
var
MyThread1: TMyThread;
begin
{ add your program here }
MyThread1:= TMyThread.Create(True);
MyThread1.start:=1;
MyThread1.finish:=100;
MyThread1.Resume;
// stop program loop
Terminate;
end;
var
Application: TMyApplication;
{$IFDEF WINDOWS}{$R test.rc}{$ENDIF}
begin
Application:=TMyApplication.Create(nil);
Application.Title:='My Application';
Application.Run;
Application.Free;
end.
unit MyThreads;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
Type
TMyThread = class(TThread)
private
protected
procedure Execute; override;
public
start,finish: integer;
Constructor Create(CreateSuspended : boolean);
end;
implementation
constructor TMyThread.Create(CreateSuspended : boolean);
begin
FreeOnTerminate := True;
inherited Create(CreateSuspended);
end;
procedure TMyThread.Execute;
var
i: integer;
begin
i:=start;
while (not Terminated) and (i<=finish) do
begin
Writeln(i);
inc(i);
if i=finish+1 then Terminate;
end;
end;
end.
But I don't know what should I do to make it in the right way...
Please help.
Thank You in advance,
Andrey Sapegin.