目录
2.1 Concurrency vs. Parallelism 并发vs.并行
2.2 Programming challenges 编程挑战
3. Multithreading Models 多线程模型
3.2 User-level threads (ULT) 用户线程
3.3 Kernel-level threads (KLT) 内核线程
3.4 Multithreading Models 多线程模型
6. Threading issues / Designing multithreaded programs
6.3 Semantics of fork() and exec()
1. Overview
OS view: A thread is an independent stream of instructions that can be scheduled to run by the OS. 一个线程是一个独立的指令流,可以由操作系统安排运行。
Software developer view: A thread can be considered as a “procedure” that runs independently from the main program. 一个线程可以被视为一个独立于主程序运行的 "程序"。
- Sequential program: a single stream of instructions in a program.
- Multi-threaded program: a program with multiple streams. 使用多内核/CPUs需要多线程。
Benefits of threads
- Takes less time to create a new thread than a process.
- Less time to terminate a thread than a process.
- Switching between two threads takes less time than switching between processes.
- Threads enhance efficiency in communication between programs.
Examples
用户在word输入文本:打开一个文件并输入文本(一个线程),文本自动格式化(另一个线程),文本自动识别拼写错误(另一个线程),文件自动保存到磁盘(另一个线程)。
Typing in a file is a process, formatting, spells checking, saving these are threads.
Threads are scheduled on a processor, and each thread can execute a set of instructions independent of other processes and threads. 线程被安排在处理器上,每个线程可以独立于其他进程和线程执行一组指令。
Thread Control Block (TCB) stores the information about a thread
它与属于同一进程的其他线程共享其代码区、数据区和其他操作系统资源,如开放文件和信号。
A thread is a basic unit of CPU utilization; it comprises a thread ID, a program counter, a register set, and a stack. 线程是CPU利用率的基本单位。
线程状态:
- Undefined: 未创建的线程处于undefined状态;
- Ready: 当线程就绪时,处于ready状态;
- Running: 同一时刻只能有一个线程处于running状态;
- Suspended: 当线程被中断运行(suspend),处于suspended状态,随后可调用resume()回归就绪状态;
- Terminated & Destroyed: 处于中断terminated状态的进程会被释放,随后处于销毁destroyed状态;
2. Multicore Programming 多核编程
Whether the cores appear across CPU chips or within CPU chips, we call these systems multicore or multiprocessor systems. Multithreaded programming provides a mechanism for more effificient use of these multiple computing cores and improved concurrency.
2.1 Concurrency vs. Parallelism 并发vs.并行
Concurrent execution on single-core system: Concurrency means multiple tasks which start, run, and complete in overlapping time periods, in no specific order. 并发意味着多个任务在重叠的时间段内启动、运行和完成,没有特定的顺序。
Parallelism on a multi-core system: A system is parallel if it can perform more than one task simultaneously. 如果一个系统可以同时执行一个以上的任务,那么它就是并行的。
并发(Concurrency)和并行 (Parallelism) 的区别:
并发是指一个处理器同时处理多个任务。
并行是指多个处理器或者是多核的处理器同时处理多个不同的任务。
并发是逻辑上的同时发生,而并行是物理上的同时发生。
来个比喻:并发是一个人同时吃三个馒头,而并行是三个人同时吃三个馒头。
2.2 Programming challenges 编程挑战
In general, five areas present challenges in programming for multicore systems:
- Identifying tasks. 这涉及到检查应用程序,以找到可以划分为独立的、并发的任务的区