Information Technology Reference
In-Depth Information
Running, suspending, and resuming threads. Threads provide the il-
lusion of an infinite number of processors. How does the operating system
implement this illusion? It needs to be able to execute instructions from each
thread so that each thread makes progress, but the underlying hardware has
only a limited number of processors|maybe only one!
To map an arbitrary set of threads to a fixed set of processors, operating
systems include a scheduler that can switch which threads are running and
which are ready but not running. For example, in Figure 4.2, a scheduler might
suspend thread 1 from processor 1, move it to the list of ready threads, and
then resume thread 5 by moving it from the ready list to run on processor 1.
Switching between threads is transparent to code being executed by the
threads. Remember that the point of the abstraction is to make each thread
appear to be a single stream of execution, so a programmer should only have
to worry about the sequence of instruction within a thread and not have to
worry about where that sequence may be (temporarily) suspended to let another
thread run.
Threads thus provide an execution model in which each thread runs on a
dedicated virtual processor with unpredictable and variable speed. From the point
of view of a thread's code, each instruction appears to execute immediately
after the preceding instruction. However, the scheduler may suspend a thread
between one instruction and the next and resume running it later. It is as if
the thread was continually running on a processor that sometimes becomes very
slow.
For example, Figure 4.3, illustrates a programmer's view of a simple program
and three (of many) possible ways that program might be executed, depending
on what the scheduler does. From the point of view of the thread, other than the
speed of execution, all of these ways are equivalent. Indeed, the thread would
typically not even know which of these (or other) executions actually occurred.
Of course, a thread's speed of execution and its interleavings with other
threads will be affected by how it is scheduled. Figure 4.4, shows a handful of
the many possible interleavings of a three thread program. Thread program-
mers should therefore not make any assumptions about the relative speed that
different threads execute.
Why \unpredictable speed"? It may seem strange to assume that a thread's
virtual processor runs at a completely unpredictable speed and to assume that
any interleavings with other threads are possible. Surely some interleavings are
more likely than others?
The reason the threads programming model adopts this assumption is to
guide programmers when reasoning about correctness. As Chapter 5 decribes,
rather than assuming that one thread at the same speed as another (or faster or
slower) and trying to write programs that coordinate threads based on their rel-
 
Search WWH ::




Custom Search