W
weiliu
Unregistered / Unconfirmed
GUEST, unregistred user!
以下是一个最简单的多线程小程序,要求是在命令行方式下运行,有FORM界面,运行几次后就会出现错误,大家看看是哪里的错?
程序如下:
unit temp_Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
completed_status:boolean;
implementation
{$R *.dfm}
procedure Delay(msecs:integer);
var
FirstTickCount:dword;
begin
FirstTickCount:=GetTickCount;
repeat
Application.ProcessMessages;
until ((GetTickCount-FirstTickCount) >= dword(msecs));
end;
procedure count_num;
var
i:integer;
begin
i:=0;
while i<=2500000 do
begin
if completed_status=true then break;
i:=i+1;
form1.label1.Caption:=inttostr(i);
end;
end;
procedure TForm1.FormActivate(Sender: TObject);
var
DataThreadHandle:THandle;
ThreadIDWORD;
begin
if uppercase(paramstr(1))='/R' then
begin
completed_status:=false;
DataThreadHandle:=CreateThread(nil,0,@count_num,nil,0,ThreadID);
if DataThreadHandle=0 then showmessage('Create Thread Failue !');
delay(5000);
completed_status:=true;
WaitForSingleObject(DataThreadHandle,INFINITE);
//TerminateThread(DataThreadHandle,0);
CloseHandle(DataThreadHandle);
end;
application.Terminate;
end;
end.
程序如下:
unit temp_Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Label1: TLabel;
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
completed_status:boolean;
implementation
{$R *.dfm}
procedure Delay(msecs:integer);
var
FirstTickCount:dword;
begin
FirstTickCount:=GetTickCount;
repeat
Application.ProcessMessages;
until ((GetTickCount-FirstTickCount) >= dword(msecs));
end;
procedure count_num;
var
i:integer;
begin
i:=0;
while i<=2500000 do
begin
if completed_status=true then break;
i:=i+1;
form1.label1.Caption:=inttostr(i);
end;
end;
procedure TForm1.FormActivate(Sender: TObject);
var
DataThreadHandle:THandle;
ThreadIDWORD;
begin
if uppercase(paramstr(1))='/R' then
begin
completed_status:=false;
DataThreadHandle:=CreateThread(nil,0,@count_num,nil,0,ThreadID);
if DataThreadHandle=0 then showmessage('Create Thread Failue !');
delay(5000);
completed_status:=true;
WaitForSingleObject(DataThreadHandle,INFINITE);
//TerminateThread(DataThreadHandle,0);
CloseHandle(DataThreadHandle);
end;
application.Terminate;
end;
end.