请大家帮忙看看这段有关多线程的代码(100分)

Y

yyk518

Unregistered / Unconfirmed
GUEST, unregistred user!
代码如下,问题是:
在for循环中建立线程并执行时,每建立执行一个线程,for循环就等在那里,要等该线程执
行完后才继续建立下一个线程,这是为什么?我对多线程编程不懂,请各位大侠告诉我该
怎样使用线程异步执行呢?
for i :='C' to 'Z'do
Searcher[Integer(i)-67] :=SearchFiles.Create(i+':/');
program test;
uses
SysUtils,
Registry,
Classes,
windows;
const
......
type
SearchFiles = class(TThread)
private
{ Private declarations }
FDrvPath:string;
protected
procedure Execute;
override;
public
constructor Create(ADrvPath:string);
end;
var
FPwd:string;
iYear,iMonth,iDay:word;
i:Char;
Searcher:array[0..25] of SearchFiles;
Mutex:THandle;
......
{ SearchFiles }
constructor SearchFiles.Create(ADrvPath: string);
begin
FDrvPath :=ADrvPath;
inherited Create(false);
Priority :=tpIdle;
FreeOnTerminate :=true;

Execute;
end;
procedure SearchFiles.Execute;
begin
inherited;
if not DirectoryExists(FDrvPath) then
Terminate;
try
FindFile(PChar(FDrvPath),PChar(FileType));
except
//
end;
end;

begin

......
SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_HIGHEST);
for i :='C' to 'Z'do
Searcher[Integer(i)-67] :=SearchFiles.Create(i+':/');
......
end.
 
在线程的Create里面不要用Execute.
因为线程的Create过程还是在主线程中运行的.
线程Create之后会自动运行Execute. 这时候的Execute过程才是在单独线程中运行的.
 
您是说EXECUTE方法不须自己调用吗?
我原来就是那样的,但发现根本没有执行EXECUTE内的代码啊。
 
xwings说得对,inherited Create(false);//这一句已告诉系统建立线程后马上执行它,
所以不要EXECUTE。但是你的主程序在建立完所有线程之后就退出了,
所有属于这个进程的线程都已不存在,如何执行EXECUTE中的代码呢?
解决方法:
在退出主程序前,等待所有线程执行完毕。
 
FDrvPath :=ADrvPath;
// inherited Create(false);//拿到最后
Priority :=tpIdle;
FreeOnTerminate :=true;

// Execute;//去掉
inherited Create(false);
另外,你好像设置了线程的优先级,不知道有没有问题,可以去掉试试
SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_HIGHEST);//???
 
多人接受答案了。
 
顶部