现在有一个像这样的多线程方案:
//global variables
var
Form1: TForm1;
ControlFile: TextFile;
MaxThreads, iThreads: integer;
MyCritical: TCriticalSection;
ControlFile由执行ReadLn的线程访问,并使用获得的行执行操作:
procedure TForm1.Button2Click(Sender: TObject);
var
HostLine: AnsiString;
FileHandle: integer;
begin
MyCritical:= TCriticalSection.Create;
MaxThreads:= 100;
iThreads:= 0;
while not(eof(ControlFile)) and (iThreads < MaxThreads) do
begin
inc(iThreads);
ReadLn(ControlFile, HostLine);
MyThread.Create(HostLine);
end;
end;
这个街区是第一个疑问。我创建了100个线程,每个创建的线程接收到文本文件的当前行。但问题是在threads.onterminate上,我执行了这个:
procedure MyThread.MainControl(Sender: TObject);
var
HostLine: string;
begin
try
MyCritical.Acquire;
dec(iThreads);
while not(eof(ControlFile)) and (iThreads < MaxThreads) do
begin
inc(iThreads);
ReadLn(ControlFile, HostLine);
MyThread.Create(HostLine);
end;
finally
MyCritical.Release;
end;
end;
我们的想法是继续创建新线程,直到文本文件完成。但是如果一个线程终止并执行此过程,那么在第一个完成之前,会发生什么?来自button2click的主线程将访问该文件,以及线程的过程。这看起来很奇怪。而关键部分应该是全局的还是本地的线程?这个程序,MainControl,在文件结束之前打开新线程,应该是全局的还是线程本地的?