尝试在单个生产者多个消费者方案中使用TThreadedQueue(Generics.Collections).(DELPHI-XE).我们的想法是将对象推入队列,让几个工作线程排空队列.
但它没有按预期工作.当两个或多个工作线程调用PopItem时,将从TThreadedQueue抛出访问冲突.
如果对PopItem的调用是使用临界区序列化的,那么一切都很好.
当然,TThreadedQueue应该能够处理多个消费者,所以我错过了什么或者这是TThreadedQueue中的一个纯粹的错误?
这是一个产生错误的简单示例.
program TestThreadedQueue;
{$APPTYPE CONSOLE}
uses
// FastMM4 in '..\..\..\FastMM4\FastMM4.pas',
Windows,
Messages,
Classes,
SysUtils,
SyncObjs,
Generics.Collections;
type TThreadTaskMsg =
class(TObject)
private
threadID : integer;
threadMsg : string;
public
Constructor Create( ID : integer; const msg : string);
end;
type TThreadReader =
class(TThread)
private
fPopQueue : TThreadedQueue<TObject>;
fSync : TCriticalSection;
fMsg : TThreadTaskMsg;
fException : Exception;
procedure DoSync;
procedure DoHandleException;
public
Constructor Create( popQueue : TThreadedQueue<TObject>;
sync : TCriticalSection);
procedure Execute; override;
end;
Constructor TThreadReader.Create( popQueue : …Run Code Online (Sandbox Code Playgroud)