2

我在使用线程运行应用程序时遇到问题,在 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.

这里是带有错误消息的图像:错误消息图像

4

1 回答 1

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}

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

方案项目1;

{$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

于 2012-10-05T03:40:48.670 回答