相关疑难解决方法(0)

如何让线程在被释放之前完成其工作?

我正在编写一个写入事件日志的线程.当应用程序关闭(正常)时,我需要确保此线程完成其作业,在它被释放之前保存日志.如果我Free直接调用该线程,它不应该立即被销毁,它应该等到线程完成并且还有其他工作要做.

这是我如何布置我的线程的执行:

procedure TEventLogger.Execute;
var
  L: TList;
  E: PEventLog; //Custom record pointer
begin
  while not Terminated do begin //Repeat continuously until terminated
    try
      E:= nil;
      L:= LockList; //Acquire locked queue of logs to be written
      try
        if L.Count > 0 then begin //Check if any logs exist in queue
          E:= PEventLog(L[0]); //Get next log from queue
          L.Delete(0); //Remove log from queue
        end;
      finally
        UnlockList;
      end;
      if E <> nil then begin
        WriteEventLog(E); //Actual call to save log
      end; …
Run Code Online (Sandbox Code Playgroud)

delphi multithreading

3
推荐指数
2
解决办法
1003
查看次数

delphi中的多线程队列?

这是我关于这个问题的第二个问题,我对此有一些麻烦.<

好吧,我只想创建有限数量的线程(在这种情况下,我想要10个线程),然后每个线程将在我的列表中选取一个名称并在我的站点中获取一些数据.

我的系统工作得很好,但我的多线程系统仍然失败=(

-

我尝试了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 …
Run Code Online (Sandbox Code Playgroud)

delphi queue multithreading

0
推荐指数
1
解决办法
5435
查看次数

标签 统计

delphi ×2

multithreading ×2

queue ×1