[ Pobierz caÅ‚ość w formacie PDF ] .See Using the main VCL/CLX thread on page 9-4 for more information on the main thread.If the global memory does not need to be shared by multiple threads, consider usingthread-local variables instead of global variables.By using thread-local variables,your thread does not need to wait for or lock out any other threads.See Usingthread-local variables on page 9-5 for more information about thread-localvariables.9-8 Dev el oper s Gui deCo o r d i n a t i n g t h r e a d sWaiting for other threadsIf your thread must wait for another thread to finish some task, you can tell yourthread to temporarily suspend execution.You can either wait for another thread tocompletely finish executing, or you can wait for another thread to signal that it hascompleted a task.Waiting for a thread to finish executingTo wait for another thread to finish executing, use the WaitFor method of that otherthread.WaitFor doesn t return until the other thread terminates, either by finishingits own Execute method or by terminating due to an exception.For example, thefollowing code waits until another thread fills a thread list object before accessing theobjects in the list:if ListFillingThread.WaitFor thenbeginwith ThreadList1.LockList dobeginfor I := 0 to Count - 1 doProcessItem(Items[I]);end;ThreadList1.UnlockList;end;In the previous example, the list items were only accessed when the WaitFor methodindicated that the list was successfully filled.This return value must be assigned bythe Execute method of the thread that was waited for.However, because threads thatcall WaitFor want to know the result of thread execution, not code that calls Execute,the Execute method does not return any value.Instead, the Execute method sets theReturnValue property.ReturnValue is then returned by the WaitFor method when it iscalled by other threads.Return values are integers.Your application determines theirmeaning.Waiting for a task to be completedSometimes, you need to wait for a thread to finish some operation rather thanwaiting for a particular thread to complete execution.To do this, use an event object.Event objects (TEvent) should be created with global scope so that they can act likesignals that are visible to all threads.When a thread completes an operation that other threads depend on, it callsTEvent.SetEvent.SetEvent turns on the signal, so any other thread that checks willknow that the operation has completed.To turn off the signal, use the ResetEventmethod.For example, consider a situation where you must wait for several threads tocomplete their execution rather than a single thread.Because you don t know whichthread 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 havethe last thread signal that they are all done by setting an event.Wr i t i ng mul t i - t hr eaded appl i c at i ons 9-9Ex e c u t i n g t h r e a d o b j e c t sThe following code shows the end of the OnTerminate event handler for all of thethreads that must complete.CounterGuard is a global critical section object thatprevents multiple threads from using the counter at the same time.Counter is a globalvariable that counts the number of threads that have completed.procedure TDataModule.TaskThreadTerminate(Sender: TObject);begin’CounterGuard.Acquire; { obtain a lock on the counter }Dec(Counter); { decrement the global counter variable }if Counter = 0 thenEvent1.SetEvent; { signal if this is the last thread }CounterGuard.Release; { release the lock on the counter }’end;The main thread initializes the Counter variable, launches the task threads, and waitsfor the signal that they are all done by calling the WaitFor method.WaitFor waits for aspecified time period for the signal to be set, and returns one of the values from Table9.2.Table 9.2 WaitFor return valuesValue MeaningwrSignaled The signal of the event was set.wrTimeout The specified time elapsed without the signal being set.wrAbandoned The event object was destroyed before the timeout period elapsed.wrError An error occurred while waiting.The following shows how the main thread launches the task threads and thenresumes when they have all completed:Event1.ResetEvent; { clear the event before launching the threads }for i := 1 to Counter doTaskThread.Create(False); { create and launch task threads }if Event1.WaitFor(20000) wrSignaled thenraise Exception;{ now continue with the main thread.All task threads have finished }Note If you do not want to stop waiting for an event after a specified time period, pass theWaitFor method a parameter value of INFINITE.Be careful when using INFINITE,because your thread will hang if the anticipated signal is never received.Executing thread objectsOnce you have implemented a thread class by giving it an Execute method, you canuse it in your application to launch the code in the Execute method.To use a thread,first create an instance of the thread class.You can create a thread instance that startsrunning immediately, or you can create your thread in a suspended state so that itonly begins when you call the Resume method.To create a thread so that it starts up9-10 Devel oper s Gui deEx e c u t i n g t h r e a d o b j e c t simmediately, set the constructor s CreateSuspended parameter to False.For example,the following line creates a thread and starts its execution:SecondProcess := TMyThread.Create(false); {create and run the thread }Warning Do not create too many threads in your application.The overhead in managingmultiple threads can impact performance
[ Pobierz całość w formacie PDF ] zanotowane.pldoc.pisz.plpdf.pisz.plmikr.xlx.pl
|