Threaded Applications

Download Report

Transcript Threaded Applications

Threaded Applications
Introducing additional threads in a
Delphi application is <Relatively>
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 (?)<1-2 Seconds> 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
Spawn session
Handle
Queries
In
order
IP
Session
Sql Query
Sql Results
Quey
And
Wait
Database
Access
• Slides and demonstration code
– http://www.innovasolutions.com.au/delphistuf/ADUGJanuary2006.htm