Threads

     

Thread Usage

Why threads?


Thread scenario: user changes sentence one of an 800-page book, then goes to make a second change. A singl-threaded program must re-format the whole book, and then return control to the user. With two threads, one formats and the other handles user input. We can add a third-thread to handle disk I/O.
Processes won't do here: they can't share the memory containing the document.

Situation is tricky: think of all those times you have clicked on the wrong link, because the mouse was live.

The Classical Thread Model

Process as group of resources versus process as thread of execution.
Threads separate the latter from the former.
An analogy: we have theaters (resources) and in them we put on plays (threads). In the process-only model, each play gets its own theater. With threads, several plays can run "at once" in a single theater, sharing lights, props, ticket booths, etc.

Per Process Per Thread
Address space Program counter
Global variables Registers
Open files Stack
Child processes State
Pending alarms
Signals and signal handlers
Accounting information

Threads have the same states as processes.

Implementing Threads in User Space

Upsides:

Downsides:

Example: Java threading and synchronized keyword.

Implementing Threads in Kernel Space

Upsides:

Downsides:

Hybrid Implementations

The programmer can put some threads in kernel space, and some in user space.

Scheduler Activations

Also tries to be the best of both worlds: here, the kernel makes a call (upcall) into user space to tell the user code that a thread has blocked.
Objection: Calls are supposed to go in the opposite direction!

Pop-up Threads

Imagine a web server, waiting for HTTP requests.

Usual approach: Have a process or a thread blocking, waiting for a request to come in.

Pop-up approach: create a thread at the moment a request arrives: the thread "pops up" just in time to handle the request.
These can take over quickly, since they have no state to restore.

Making Single-Threaded Code Multi-Threaded

Why this is tricky:

Shared resource: Bulletin board example.
Non-reentrant library calls: E.g, writing a file with fwrite().
Signals: Who gets the signal? The OS doesn't know about user-level threads.

The point: Conversion is hard work!

Credits

External Links