Information Technology Reference
In-Depth Information
Chapter 5
Synchronizing Access to
Shared Objects
Multi-threaded programs extend the traditional, single-threaded programming
model so that each thread provides a single sequential stream of execution com-
posed of familiar instructions. If we only have independent threads that operate
Definition: independent
threads
on completely separate subsets of state, then we can reason about each thread
separately. In this case, writing and reasoning about independent threads differs
little from writing and reasoning about a series of independent, single-threaded
programs.
However, most multi-threaded programs have both both per-thread state
(e.g., a thread's stack and registers) and shared state (e.g., shared variables on
the heap). Cooperating threads read and write shared state.
Definition: Cooperating
threads
Sharing state among threads is useful because it allows threads to communi-
cate, to coordinate work, and to share information. For example, in our Earth
Visualizer example in the previous chapter, once one thread has finished down-
loading a detailed image from the network, it needs to share that image data
with a rendering thread that draws the new image on the screen.
Unfortunately, when cooperating threads use shared state, writing correct
multi-threaded programs becomes much more dicult. Most programmers are
used to thinking \sequentially" when reasoning about programs. For example,
we often reason about the series of states traversed by a program as a sequence
of instructions is executed. But this sequential model of reasoning breaks down
in programs with cooperating threads for three reasons.
1. Program execution depends on the interleavings of threads' access to
shared state.
For example, if two threads write a shared variable, one thread with the value
179
 
Search WWH ::




Custom Search