这是我对这件事的第二个问题,即时通讯有一些麻烦。我只是想创建有限数量的线程(在这种情况下,我想要10个线程),然后每个线程都会在列表中选取一个名称,并在我的站点中获取一些数据。delphi中的多线程队列?
我的系统运行得很好,但我的多线程系统仍然无法=(
-
我试图张贴LU RD的代码,但主线程不等待线程完成排队,只是停止=(
代码:
uses
Classes,SyncObjs,Generics.Collections;
Type
TMyConsumerItem = class(TThread)
private
FQueue : TThreadedQueue<TProc>;
FSignal : TCountDownEvent;
protected
procedure Execute; override;
public
constructor Create(aQueue : TThreadedQueue<TProc>; aSignal : TCountdownEvent);
end;
constructor TMyConsumerItem.Create(aQueue: TThreadedQueue<TProc>; aSignal : TCountDownEvent);
begin
Inherited Create(false);
Self.FreeOnTerminate := true;
FQueue := aQueue;
FSignal := aSignal;
end;
procedure TMyConsumerItem.Execute;
var
aProc : TProc;
begin
try
repeat
FQueue.PopItem(aProc);
if not Assigned(aProc) then
break; // Drop this thread
aProc();
until Terminated;
finally
FSignal.Signal;
end;
end;
procedure DoSomeJob(myListItems : TStringList);
const
cThreadCount = 10;
cMyQueueDepth = 100;
var
i : Integer;
aQueue : TThreadedQueue<TProc>;
aCounter : TCountDownEvent;
function CaptureJob(const aString : string) : TProc;
begin
Result :=
procedure
begin
// Do some job with aString
end;
end;
begin
aQueue := TThreadedQueue<TProc>.Create(cMyQueueDepth);
aCounter := TCountDownEvent.Create(cThreadCount);
try
for i := 1 to cThreadCount do
TMyConsumerItem.Create(aQueue,aCounter);
for i := 0 to myListItems.Count-1 do begin
aQueue.PushItem(CaptureJob(myListItems[i]));
end;
finally
for i := 1 to cThreadCount do
aQueue.PushItem(nil);
aCounter.WaitFor; // Wait for threads to finish
aCounter.Free;
aQueue.Free;
end;
end;
我的其他问题:Multi Thread Delphi
使用Delphi XE3的Im。
请添加代码来演示您的问题。这里的代码工作正常。 – 2013-04-25 06:05:18
OmniThreadLibrary同时拥有线程池和无锁多线程队列类 – 2013-04-25 10:37:38
@LU RD,问题是主线程在线程完成工作之前只是推零。我真的不知道为什么=(.man线程队列很难做到._。 – Kirito94 2013-04-25 13:54:21