Amos
Amos

Reputation: 1341

Delphi: Wait for threads to finish

I read this article about creating a thread pool: http://delphi.about.com/od/kbthread/a/delphi-thread-pool-example-using-asynccalls.htm

The reason I use the author's version is because of the waitAll function he made. This is working OK except for the fact that calling waitAll blocks the GUI thus losing the idea of using threads. Any hint/tip on what's needs to be changed? I emailed the author but he didn't respond.

I thought of adding Application.ProcessMessages; in the waiting loop but I don't think it's a good idea. Thanks

Upvotes: 2

Views: 8978

Answers (2)

Sir Rufo
Sir Rufo

Reputation: 19096

The simple pattern for task creation and waiting until the work is done is shown by this pseudo code

// create a management task
task.Create(
  procedure
  var
    tasks : TArray<task>;
  begin
    // synchronized action to the main thread
    // before the work begins
    TThread.Queue(nil,
    procedure
    begin
      SomeForm.Button.Enabled := False;
    end);

    // creation of the tasks doing the real work
    tasks := ...

    // wait until the work is done
    WaitForAll( tasks );

    // synchronized action to the main thread
    // after the work hs finished
    TThread.Queue(nil,
    procedure
    begin
      SomeForm.Button.Enabled := True;
    end);
  end );

And this is just a pseudo code translation of davids answer (second part).

Upvotes: 4

David Heffernan
David Heffernan

Reputation: 612804

Waiting for all tasks to complete in the GUI thread is the wrong way to do it. Don't do that.

Instead arrange for each task to signal completion to the main thread. When the main thread receives the final completion signal, it can perform whatever task is needed to executed. You might make a counter of all the tasks that are to run. Each task that completes signals the main thread which decrements the count. When it reaches zero they are all done

Or create another background thread with the sole task of waiting on all the other tasks. That's fine in a background thread as it won't block the UI. When that wait completes, send a message to the UI thread.

Upvotes: 6

Related Questions