Delphi XE7 Android在运行约20000次后创建线程错误



感谢您的时间。

首先简单的代码发布。

tsubthread的代码

TSubThread = class(TThread)
protected
  procedure Execute; override;
public
  constructor Create;
  destructor Destroy; override;
end;
procedure TSubThread.Execute;
begin
// do nothing
end;
constructor TSubThread.Create;
begin
  inherited Create(True);
  Self.FreeOnTerminate:= False;
end;

tmainthread的代码

TMainThread = class(TThread)
private
  FCounterOK,
  FCounterErr:int64;
  function FGetCounterOK:Int64;
  function FGetCounterErr:Int64;
protected
  procedure Execute; override;
public
  property CountOK:Int64 read FGetCounter;
  property CountErr:Int64 read FGetCounterErr;
  constructor Create;
  destructor Destroy; override;
end;
function TMainThread.FGetCounterOK:Int64;
begin
  result:= TInterlocked.Read(Self.FCounterOK);
end;
function TMainThread.FGetCounterErr:Int64;
begin
  result:= TInterlocked.Read(Self.FCounterErr);
end;
procedure TMainThread.Execute;
const
  CSTMaxThreads = 20;
var
  i: Integer;
  los:TArray<TSubThread>;
begin
  try
    while not Self.Terminated do
    begin
      //Create instance of TSubThread and append to DynArray
      while Length(los) < CSTMaxThreads do
      begin
        try
          l:= TSubThread.Create;
          los:= los + [l];
          l.Start;
          TInterLocked.Increment(Self.FCounterOK);
        except on E:System.SysUtils.Exception do
          TInterLocked.Increment(Self.FCounterErr);
        end;
      end;
      for i:= Length(los)-1 downto 0 do
      begin
      // Free thread Object
        if los[i].Finished then
        begin
          los[i].DisposeOf;
          los[i]:= nil;
          Delete(los,i,1);
        end;
      end;
    end;
  finally
    // MainThread  Terminated, Free all.
    for i := Length(los)-1 downto 0 do
    begin
      los[i].DisposeOf;
      los[i]:= nil;
    end;
    delete(los,0,Length(los));
  end;
end;

在Android平台上运行了约1800000〜2000000次(通过Counterok和Countererr属性),创建TsubThread Rise Deface例外,并带有E.ToString ="创建错误:再试一次。" ...并且同一程序在Windows上运行完美。和iOS。代码是否错误?

我很确定这里的问题是您要产生的线程太多,并且用尽了资源来支持其存在。执行完成后,但在清理实际的基础线程之前完成了TTHREAD集合。处置将调用驱动器,但这仍然只使用waitfor,这些waitfor检查完成,因此仍可能会为基础线程留下出色的清理。管理所有平台上的线程的破坏总是存在问题,我很确定您会发现这是这里正在发生的事情。很长一段时间以来,我一直求助于内部重复使用和自由终止的线程池,以避免这些问题。

最新更新