我在使用线程运行应用程序时遇到问题,在 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.
这里是带有错误消息的图像:错误消息图像