H
H
HemulGM2020-02-07 11:39:36
Delphi
HemulGM, 2020-02-07 11:39:36

How to let a secondary thread do the synchronization?

Suppose we have one secondary thread. What he does is not important. The important thing is that inside it there is a method that is executed through synchronization, i.e. is executed in an external thread.
Further, if the completion of the program suddenly began, we must complete the secondary thread in order to release everything that it has done there and complete the program already.
The problem is this: If the secondary thread was waiting for a synchronization signal at the time the program ended, i.e. he was ready to execute the method through synchronization, but waited until the main thread allowed, then the result is a deadlock, because the main thread is waiting for the completion of the secondary, and the secondary is waiting for synchronization from the main.

if Assigned(FThread) then
  begin
    FThread.Terminate;
    FThread.Free; <- тут, при освобождении потока выполняется WaitFor для этого потока
    FThread := nil;
  end;

Once again, with FThread.Free; the main thread waits (WaitFor) the completion of the secondary thread, which is waiting for synchronization with the main thread.

I also tried like this:
if Assigned(FThread) then
  begin
    FThread.Terminate;
    TThread.Current.Yield;  //с или без этого
    while not FLongPollStopped do  <- флаг, который меняет второстепенный поток при завершении
    begin
      CheckSynchronize(10000);  //с или без этого
      Application.ProcessMessages;
    end;
    FThread.Free;
    FThread := nil;
  end;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
Hemul GM, 2020-02-07
@HemulGM

I found the answer myself. If you do not give and intercept the termination of the program (for example, when closing the main window), i.e. CanClose := False;and stop the thread (i.e. set a flag) and wait until it completes, then everything ends without problems and no blocking occurs. And then you can call the end of the entire program.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question