Threaded Applications Introducing additional threads in a Delphi application is easy
Threaded Applications A Thread is? Why would you introduce additional threads? Basic Thread Code Variables and Thread Safe Code Some Thread Models - Communication
What is a Thread ? Simple Program – Sequential Steps –Waits to read data –Single “Thread” Windows OS runs programs “at the same time” –Time allocation, System Waits The OS also allows sections of a program to run independently in the same way. Each TThread Object introduces an additional independent set of processor steps (thread) within the application.
Why Introduce Multiple Threads? Users are no longer prepared to wait –If more than (?) then Thread More efficient –Actions happen in other Thread wait cycles Many things lend themselves to “Background” running –Large database reports –Internet access Can make things simpler –Less need for state engines
Basic Thread Code Inherit from TThread Object –Override the Execute Routine. –Handle exceptions within Execute –Keep Execute Thread safe Must free TThread Object or the Application will not close –Must allow Execute to terminate
Thread Safety Code is unsafe when a variable can be changed by separate threads in an uncontrolled manner and the change affects the program flow. Procedure Local Variables are safe Object Private and Protected variables and objects can be managed Thread Local >> threadvar X: Integer; –Global Variable Equivalent ???
Synchronization Objects Used to manage access to variables TCriticalSection –Protect blocks of code Acquire Release TSimpleEvent –One Thread initiates action then waits until other thread has set the event
Synchronize Routine Only works with VCL thread You get to pass a procedure of object without parameters The procedure needs to be able to establish its context to access variables The calling thread is suspended until the procedure returns
Thread Communication Models Separate (console) process Single Run –Recover Results in OnTerminate Server with Post Messages –Post results home Server with Synchronized callback –Call VCL Thread with results Multiplexed Server –Wait for thread to complete action
Threads to Multiplex Listen on Port IP Session Database Access Sql Query Sql Results Quey And Wait Spawn session Handle Queries In order
Slides and demonstration code –