To wait for a task to complete

  1. Create a TEvent object of global scope.
  2. When a thread completes an operation other threads are waiting for, have the thread call TEvent.

SetEvent.

3. To turn off the signal, call TEvent.ResetEvent.

The following example is an OnTerminate event handler that uses a global counter in a critical section to keep track of the number of terminating threads. When Counter reaches 0, the handler calls the SetEvent method to signal that all processes have terminated:

procedure TDataModule.TaskTerminateThread(Sender: TObject); begin

  1. Acquire; {obtain a lock on the counter} Dec(Counter); {decrement the global counter variable} if Counter = 0 then
  2. SetEvent; {signal if this is the last thread} CounterRelease; {release the lock on the counter}

end;

The main thread initializes Counter, launches the task threads, and waits for the signal that they are all done by calling the WaitFor method. WaitFor waits a specified time period for the signal to be set and returns one of the values in the table below.

The following code example shows how the main thread launches the task threads and resumes when they have completed.

  1. ResetEvent; {clear the event before launching the threads} for i := 1 to Counter do
  2. Create(False); {create and launch the task threads} if Event1.WaitFor(20000) <> wrSignaled then raise Exception; {continue with main thread}

Note: If you do not want to stop waiting for an event handler after a specified time period, pass the WaitFor method a parameter value of INFINITE. Be careful when using INFINITE, because your thread will hang if the anticipated signal is never received.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment