Delphi 多线程问题 急~~~~

来源:百度知道 编辑:UC知道 时间:2024/06/24 13:08:02
帮忙看看我的为什么会挂掉,我的程序本不是这样,源代码太长,但一旦出现多个线程来查找一个文件夹,就会挂掉,出什么 access violation at.....

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
type pa=^integer;
var
Form1: TForm1;

implementation

{$R *.dfm}
procedure p(pa:pint);stdcall;
var a:integer;sr:TSearchRec;
begin
a:=pa^;
if Findfirst('D:\Windows\*.*',faAnyFile,sr)=0 then
while Findnext(sr)=0 do
inc(a);
end;
procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
begin
for i:=1 to 100 do
CreateThread(nil,0,@p,@i,0,PDWord(nil)^);
end;

end.

问题出在循环控制变量i上、
这样做,所有的线程参数都指向i,

但是创建的线程并不会马上被调度。
而且Delphi的局部变量是保存在堆栈里的,
如果你看汇编可以看到,在函数结束的地方,局部变量都会被销毁掉、、
因此在线程里面引用,自然就是无效的地址了、

你可以这样做:
创建线程的时候不要传递指针:
CreateThread(nil,0,@p,pointer(i),0,PDWord(nil)^);

然后线程里面:
procedure p(pa:pointer);stdcall;
var a:integer;sr:TSearchRec;
begin
a:=integer(pa);
......

这样应该就可以了、、

感觉CreateThread写的不规范。。。