Chapter 4: Threads & Concurrency
线程和并发
线程(Thread)概念
进程是资源分配的基本单位,线程是处理器调度的基本单位,线程又叫轻型进程
进程是为线程提供资源的,线程必须在进程当中
线程定义为进程内一个执行单元或一个可调度实体。
-
特点
- 拥有少量的系统资源(资源是分配给进程)
- 一个进程中的多个线程可并发执行
- 进程可创建线程执行同一程序的不同部分
- 系统开销小、切换快,进程的多个线程都在进程的地址空间活动
threads shares same of process:code section, data section, operating-system resources
Multithreading Models
User Threads(用户级线程)
不依赖于OS内核(内核不了解用户线程的存在),应用进程利用线程库提供创建、同步、调度和管理线程的函数来控制用户线程
- 用户线程的维护由应用进程完成
- 内核不了解用户线程的存在
- 用户线程切换不需要内核特权
- 一个线程发起系统调用而阻塞,则整个进程在等待
Kernel Threads (内核级线程)
依赖于OS核心,由内核的内部需求进行创建和撤销。
一个线程发起系统调用而阻塞,不会影响其他线程。时间片分配给线程,所以多线程的进程获得更多CPU时间。
- 内核维护进程和线程的上下文信息
- 线程切换由内核完成
- 时间片分配给线程,所以多线程的进程获得更多CPU时间
- 一个线程发起系统调用而阻塞,不会影响其他线程的运行
Multithreading Models
Many-to-One Model
Many user-level threads mapped to single kernel thread
OS is not aware of user-level threads, OS thinks each process contains only a single thread of control
Disadvantages:Entire process blocks when one thread blocks
One-to-One
Each user-level thread maps to kernel thread
OS provides each user-level thread with a kernel thread
Each kernel thread scheduled independently
Thread operations (creation, scheduling, synchronization) performed by OS
Advantages:Each kernel-level thread can run in parallel on a multiprocessor,When one thread blocks, other threads from process can be scheduled
Disadvantages:Higher overhead for thread operations
Many-to-Many Model
Allows many user level threads to be mapped to many kernel threads
Allows the operating system to create a sufficient number of kernel threads
Two-level Model
Similar to M:M, except that it allows a user thread to be bound to kernel thread
Thread Libraries
Thread library provides programmer with API for creating and managing threads
Implicit Threading(隐式多线程)
将线程的创建与管理交给编译器和运行时库来完成,而不是手动完成