Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you detect that a TEvent has been set?

The Delphi XE2 documentation says this about TEvent:

Sometimes, you need to wait for a thread to finish some operation rather than waiting for a particular thread to complete execution. To do this, use an event object. Event objects (System.SyncObjs.TEvent) should be created with global scope so that they can act like signals that are visible to all threads.

When a thread completes an operation that other threads depend on, it calls TEvent.SetEvent. SetEvent turns on the signal, so any other thread that checks will know that the operation has completed. To turn off the signal, use the ResetEvent method.

For example, consider a situation where you must wait for several threads to complete their execution rather than a single thread. Because you don't know which thread will finish last, you can't simply use the WaitFor method of one of the threads. Instead, you can have each thread increment a counter when it is finished, and have the last thread signal that they are all done by setting an event.

The Delphi documentation does not, however, explain how another thread can detect that TEvent.Set event was called. Could you please explain how to check to see if TEvent.Set was called?

like image 630
Mike Jablonski Avatar asked Dec 21 '12 15:12

Mike Jablonski


1 Answers

If you want to test if an event is signaled or not, call the WaitFor method and pass a timeout value of 0. If the event is set, it will return wrSignaled. If not, it will time out immediately and return wrTimeout.

Having said that, the normal usage of an event is not to check whether it's signaled in this manner, but to synchronize by blocking the current thread until the event is signaled. You do this by passing a nonzero value to the timeout parameter, either the constant INFINITE if you're certain that it will finish and you want to wait until it does, or a smaller value if you don't want to block for an indefinite amount of time.

like image 185
Mason Wheeler Avatar answered Nov 13 '22 01:11

Mason Wheeler