Information Technology Reference
In-Depth Information
not write programs that do this. Automatic variables (sometimes called \local
variables" with good reason) are allocated on the stack as part of a procedure
invocation. If one thread passes a pointer or reference to one of its automatic
variables to another thread and later returns from the procedure where the
automatic variable was allocated, then that second thread now has a pointer
into a region of the rst thread's stack that may now be used for other purposes.
You might be tempted to argue that for a particular program, you know that
the a procedure won't return until all of the threads with which it is sharing an
object are done using that object and that sharing one of the procedure's local
variables is safe. The problem with this argument is that someday the code may
change, introducing a dangerous and subtle bug. When sharing dynamically-
allocated variables, it is best to stay in the habit of only sharing variables from
the heap and never sharing variables from the stack across threads.
Exercises
2. Precisely describe the set of possible outputs that could occur when the
program shown in Figure 5.5
is run.
3. Suppose that a programmer mistakenly creates an automatic (aka local)
variable v in one thread t1 and passes it to another thread t2. Is it possible
for a write by t1 to some variable other than v will change the state of v as
observed by t2? If so, explain how this can happen and give an example.
If not, explain why not.
4. Suppose that a programmer mistakenly creates an automatic (aka local)
variable v in one thread t1 and passes it to another thread t2. Is it possible
for a write by t2 to v will cause t2 to execute the wrong code? If so, so,
explain how. If not, explain why not.
5.4
Condition variables: Waiting for a change
Condition variables provide a way for one thread to wait for another thread to
take some action. For example, in the thread safe queue example in Figure 5.3,
rather than returning an error when we try to remove an item from an empty
queue, we might want to wait until the queue is non-empty and always return
an item.
Similarly, a web server might want to wait until a new request arrives, a
word processor might want to wait for a key to be pressed, a weather simulator's
coordinator thread might wait for the worker threads calculating temperatures
 
Search WWH ::




Custom Search