Lazarus Linux Ubuntu上的线程

时间:2012-10-04 18:56:51

标签: linux multithreading lazarus

当我使用线程运行应用程序时遇到问题,在Windows上运行正常,但是当我在Linux Ubuntu 12.04上运行它时,我的应用程序崩溃了。

这只是一个非常小的应用程序,只是为了理解线程。

创建线程时,我的应用程序崩溃了。

这里是代码:

unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
  ComCtrls;

type

  { TMyThread }

  TMyThread = class(TThread)
  private
    fStatusText: string;
    procedure CambiaLabel();
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: boolean);
  end;

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Label1: TLabel;
    ProgressBar1: TProgressBar;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);

    procedure FormCreate(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
     miHilo: TThread;
  end;


var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TMyThread }
procedure TMyThread.CambiaLabel();
begin
    Form1.Label1.Caption:=fStatusText;

        Form1.ProgressBar1.StepIt;

    if Form1.ProgressBar1.Position = Form1.ProgressBar1.Max then begin
       Form1.miHilo.Terminate;
       Form1.ProgressBar1.Position := 0;
    end;
end;

procedure TMyThread.Execute;
var
  newStatus : string;
begin
  fStatusText := 'TMyThread comenzando...';
  fStatusText := 'TMyThread Corriendo ...';
  while (not Terminated) and (true {any condition required}) do begin

    //here goes the code of the main thread loop

     Synchronize(@CambiaLabel);

  end;
end;

constructor TMyThread.Create(CreateSuspended: boolean);
begin
  FreeOnTerminate := True;
  inherited Create(CreateSuspended);
end;

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);

begin

    if miHilo <> nil then begin
   ShowMessage('Ya se esta ejecutando');
   end
   else begin
   miHilo := TMyThread.Create(false);
   end;

end;

procedure TForm1.Button2Click(Sender: TObject);
begin
   if miHilo <> nil then begin
   miHilo.Terminate;
   ShowMessage('Hilo terminado');
   miHilo:=nil;
   end;
end;



procedure TForm1.FormCreate(Sender: TObject);
begin

end;





end.

此处包含错误消息的图片:error message image

1 个答案:

答案 0 :(得分:2)

我找到了解决方案,我在我的项目的.lpr文件中遗漏了一些东西,我使用的是OS OS Unix,如Linux,OsX,freebsd,你必须在你的.lpr文件中添加一行:

这是普通文件:

program project1;

{$mode objfpc}{$H+}


uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Interfaces, // this includes the LCL widgetset
  Forms, Unit1
  { you can add units after this };
  .
  .
  .

这是您必须添加的行 {$ define UseCThreads}

所以你的文件应该是这样的:

program project1;

{$mode objfpc}{$H+}
{$define UseCThreads}

uses
  {$IFDEF UNIX}{$IFDEF UseCThreads}
  cthreads,
  {$ENDIF}{$ENDIF}
  Interfaces, // this includes the LCL widgetset
  Forms, Unit1
  { you can add units after this };
  .
  .
  .

这就是它现在有效,感谢答案和提示; D