Delphi threads deadlock

后端 未结 5 750
野性不改
野性不改 2020-12-23 18:10

I am having a problem sometimes with a deadlock when destroying some threads. I\'ve tried to debug the problem but the deadlock never seems to exist when debugging in the ID

5条回答
  •  独厮守ぢ
    2020-12-23 18:40

    It's simple:

    TMyThread = class(TThread)
    protected
      FIsIdle: boolean; 
      procedure Execute; override;
      procedure MyMethod;
    public
      property IsIdle : boolean read FIsIdle write FIsIdle; //you should use critical section to read/write it
    end;
    
    procedure TMyThread.Execute;
    begin
      try
        while not Terminated do
        begin
          Synchronize(MyMethod);
          Sleep(100);
        end;
      finally
        IsIdle := true;
      end;
    end;
    
    //thread destroy;
    lMyThread.Terminate;
    while not lMyThread.IsIdle do
    begin
      CheckSynchronize;
      Sleep(50);
    end;
    

提交回复
热议问题