Multithreading

Multithreading

Multithreading refers to the ability of an OS to support multiple, concurrent paths of execution within a single process.

Is a technique in which a process, executing an application, is divided into threads that can run concurrently.

Multithreading is useful for applications that perform a number of essentially independent tasks that do not need to be serialized.

Benefits of threads:

  • Takes less time to create a new thread than a process
  • Can skip resource allocation through the kernel
    • ~10x faster
  • Less time to terminate a thread than a process
  • Don’t have to release resources through the kernel
  • Less time to switch between two threads within the same process
  • More efficient communication between multiple execution entities
  • Threads within the same process share memory

An example

A database server that listens for and processes numerous client requests. With multiple threads running within the same process, switching back and forth among threads involves less processor overhead than a major process switch between different processes. Threads are also useful for structuring processes that are part of the OS kernel as described in subsequent chapters.

Processes vs. Threads

Processes:

  • Have a virtual address space which holds the process image
  • Protected access to processors, other processes, files, and I/O resources

Threads:

  • An execution state
  • Saved thread context when not running
  • Has an execution stack
  • Some per-thread static storage for local variables
  • Access to the memory and resources of its process

All threads within a process share this!

Difference of threads and processes from the point of view of process management:

Note

In multithreaded environment, there is still a single process control block and user address space associated with the process, but now there are separate stacks for each thread, as well as a separate control block for each thread containing register values, priority, and other thread-related state information.

Thus, all of the threads of a process share the state and resources of that pro- cess. They reside in the same address space and have access to the same data. When one thread alters an item of data in memory, other threads see the results if and when they access that item. If one thread opens a file with read privileges, other threads in the same process can also read from that file.

Notice, there are a kernel stack for each thread in multithreaded process model, since each thread might need to call some functions in the kernel individually.

We can create a new process as an alternative to creating a thread instead, but there are tradeoffs.

Benefits of having threads: Thread

Disadvantages:

  • Want to be selective about the treads
  • Isolation