@Author:Y4tacker
@Time:2021/4/2
Operating System(四) – Threads
Introduction
- Resource of ownership is referred to as a process or task(进程或者任务)
- Dispatching is referred to as a thread or lightweight process(线程或轻量进程)
Unit of Scheduling/Execution
Each thread has:
- An execution state (running, ready, etc.)
- 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
Single-Thread
Single-threaded approach refers to the traditional approach of a single thread of execution per process(单进程单线程), in which the concept of a thread is not recognized
- MS-DOS supports a single thread
- Some UNIX supports multiple user processes but only supports one thread per process
Multithreading
Multithreading refers to the ability of an OS to support multiple threads of execution within a single process
Benefits of Threads
- Takes less time to create a new thread than a process (创建快)
- Less time to terminate a thread than a process (结束快)
- Less time to switch between two threads within the same process (切换快)
- Since threads within the same process share memory and files, they can communicate with each other without invoking the kernel (通信快)
Threads are Affected by Many Process Action
- Suspending a process involves suspending all threads of the process since all threads share the same address space
- Termination of a process, terminates all threads within the process
Thread States
Operations associated with a change in thread state
- Spawn(派生)
- Spawn one with the creating of process
- spawn another thread later when needed
- Block(阻塞)
- Unblock(解除阻塞)
- Finish
- Deallocate register context and stacks
User-Level Threads (ULT,用户级线程)
- All thread management is done by the application
- The kernel is not aware of the existence of threads
- Multithread implemented by a threads library(线程库)
- threads library一组供应用程序共享的应用级别的函数
Advantages
- Less overhead of two mode switches(user mod and kernel mode)
- Scheduling can be application specific
(调度与应用程序相关,不同的应用程序可以采用不同的线程调度策略) - ULTs can run on any operating system
Disadvantages
- One thread is blocked, all other threads of the process are blocked in fact
- The process is block
- A multithreaded application cannot take advantage of multiprocessing
- As the unawareness of threads by the kernel
Kernel-Level Threads(内核级线程)
- Kernel maintains context information for the process and the threads
- Scheduling is done on a thread basis(线程池)
Over the disadvantages of KLT
- Overcomes the two principal drawbacks of the ULT
- Multiple threads in one process can simultaneously run on multiple processors
- One thread blocked cannot make the other threads within the same process blocked
Disadvantages of KLT to ULT
The principal disadvantage is that transfer of control from one thread to another within the same process requires a mode switch(模式切换) to the kernel