An Introduction to Programming with Threads
This paper provides an introduction to writing concurrent programs
with threads. The author bases his discussion on the choices made
in the Topaz system at DEC SRC.
- A thread is a single sequential flow of control. Multiple
threads execute within a single address space.
- Concurrency can be achieved through the use of a lightweight
multi-threading facility. Concurrency is good for multiple
processors; driving slow devices such as disks, networks,
terminals, and printers; dealing with human users; building a
distributed system with shared network servers; and reducing the
latency of operations.
- A multi-threading facility has four major mechanisms:
- Thread creation (Fork)
- Mutual exclusion or critical section (Mutex)
- Condition variables (Wait, Signal, Broadcast)
- Alerts
- Mutex
- When to use:
- To protect mutable data that will be accessed
concurrently. Mutex synchronizes access through
serialization.
- Think of the mutex as protecting the invariant of
the associated data.
- Problems:
- Cheating
- Deadlock
- Poor performance through lock conflicts
- Condition Variable
- When to use:
- When you want to schedule the way in which multiple
threads access some shared resource, and the simple
one-at-a-time mutual exclusion provided by mutexes is
not sufficient.
- Problems:
- Spurious wake-ups
- Spurious lock conflicts
- Starvation
- Deadlock
- Other problems: If you have significantly more threads ready
to run than there are processors, you will usually find that
your performance degrades.
Elaine Cheong
Last modified: Mon Jul 2 23:47:54 PDT 2001