uses Classes, SyncObjs;type TItem = class Data: Integer; end; TProducer = class(TThread) private FQueue: TThreadedQueue<TItem>; protected procedure Execute; override; public constructor Create(AQueue: TThreadedQueue<TItem>); end; TConsumer = class(TThread) private FQueue: TThreadedQueue<TItem>; protected procedure Execute; override; public constructor Create(AQueue: TThreadedQueue<TItem>); end;constructor TProducer.Create(AQueue: TThreadedQueue<TItem>);begin inherited Create(False); FQueue := AQueue;end;procedure TProducer.Execute;var I: Integer; Item: TItem;begin for I := 1 to 100 do begin Item := TItem.Create; Item.Data := I; FQueue.Enqueue(Item); Sleep(10); end;end;constructor TConsumer.Create(AQueue: TThreadedQueue<TItem>);begin inherited Create(False); FQueue := AQueue;end;procedure TConsumer.Execute;var Item: TItem;begin while not Terminated do begin if FQueue.TryDequeue(Item) then begin WriteLn(Format('Data: %d', [Item.Data])); Item.Free; Sleep(20); end else Sleep(10); end;end;var Queue: TThreadedQueue<TItem>; Producer: TProducer; Consumer: TConsumer;begin Queue := TThreadedQueue<TItem>.Create; try Producer := TProducer.Create(Queue); Consumer := TConsumer.Create(Queue); try Producer.Start; Consumer.Start; Producer.WaitFor; Consumer.Terminate; Consumer.WaitFor; finally Producer.Free; Consumer.Free; end; finally Queue.Free; end;end.
这是一个使用线程安全队列 TThreadedQueue
来实现生产者消费者模型的示例。TProducer
线程生成数据并将其添加到队列中,而 TConsumer
线程从队列中获取数据并处理