【发布时间】:2013-03-25 18:37:39
【问题描述】:
我在 delphi 中遇到多线程问题。我有一个名称列表(大约 2.000 个名称),我需要获取我网站中每个名称的一些数据。我的系统运行良好,除了线程控制。
我想创建 10 个线程,当某个线程终止时,创建另一个……直到列表结束。
var
Form1: TForm;
tCount: Integer; //threads count
implementation
type
TCheck = class(TThread)
public
constructor Create(Name: string);
destructor Destroy; Override;
protected
procedure Execute; Override;
end;
MainT = class(TThread)
protected
procedure Execute; Override;
end;
destructor TCheck.Destroy;
begin
Dec(tCount);
end;
procedure MainT.Execute;
var
i: Integer;
Load: TStringList;
begin
Load:=TStringList.Create;
Load.LoadFromFile('C:\mynames.txt');
for i:= 0 to Load.Count -1 do
begin
if tCount = 10 then //if we have 10 threads running...
begin
repeat
Sleep(1);
until tCount < 10;
end;
TCheck.Create(Load.Strings[i]);
TCheck.Start;
Inc(tCount);
end;
end; // end of procedure
好吧,我没有放 TCheck.Constructor,因为问题是我检查创建线程数的方法。我的意思是,我的软件只是停止,没有任何错误消息,有时检查 500 个名称,有时检查 150 个名称...
抱歉英语不好。
【问题讨论】:
-
你能发布 TCheck ctor 吗?
-
另外,如果您想要 10 个线程,请创建 10 个线程并让它们通过排队处理您的所有工作。不要不断地创建/终止/销毁它们。忘记 tCount 和微管理线程。
-
是的。您需要一个填充线程安全队列的生产者和 10 个消耗它的消费者。
-
@Chris Thornton,线程安全 TStringList 的例子太可怕了 :)
-
@Abelisto '忘记 tCount 和微管理线程' - 这包括 tCount 不是线程安全的事实。使 tCount 线程安全的最好方法是根本不使用它。
标签: multithreading delphi