Chapter
5 - Threads
A thread
of execution is the smallest
unit of computation that can be scheduled to run by the operating
system or virtual machine. Threads are different than
processes. A process may be thought of as an entire program
in execution. Threads are at a finer level of granularity.
A single program may have many threads contributing to its
execution. Threads the threads for a program share its global
variables and code. Because they are executing independently
of each other, each thread gets its own call stack.
Threads are related to event based programs in a number of ways:
First, responsiveness
is a critical property of many event based systems. By
responsiveness we mean that there is a stream of events taking place
that the system needs to respond to each in a timely fashion. If
the system falls significantly behind, there will be a backlog of
events and the system is said to unresponsive. Consider a
simple GUI, for example. When the user clicks the OK button,
she expects the program to respond quickly. If the program
sits there, unresponsive for 30 seconds, she may very well click the OK
button several more times, before shutting down the application.
Lack of responsiveness can arise for a number of reasons. One
is long running event handlers may 'steal' all the event handling CPU
cycles, making it impossible for the event handling thread to respond
to new incoming events. A solution to this problem is to
create a new thread for all long running handlers.
Unfortunately, multi-threading can introduce new problems.
Race conditions, deadlock, and other synchronization issues
are the bane of many programs. It isn't possible to give
these topics a thorough treatment in one short chapter, and readers are
encouraged to pick up a good operating systems text to gain a deeper
understanding.
Threads may also be thought of as a type of event based system.
Threads have control state. Threads execute in a
nondeterministic order. Threads are loosely coupled to other
threads, and threads respond to system events, e.g. operating system
timers.
Chapter
5 - Threads