160 likes | 279 Views
第三讲 线程. 中国科学技术大学计算机系 陈香兰 xlanchen@ustc.edu.cn Fall 2013. 内容提要. 为什么要引入线程? 什么是线程? Benefits User and Kernel Threads Multithreading Models Solaris 2 Threads Reading : 汤子瀛,二版, 2.4 Operating Systems Concepts , 7th , chapter4. 为什么要引入线程?. Review 进程 考虑一个 Web 服务器
E N D
第三讲 线程 中国科学技术大学计算机系 陈香兰 xlanchen@ustc.edu.cn Fall 2013
内容提要 • 为什么要引入线程? • 什么是线程? • Benefits • User and Kernel Threads • Multithreading Models • Solaris 2 Threads • Reading: • 汤子瀛,二版,2.4 • Operating Systems Concepts,7th,chapter4
为什么要引入线程? • Review 进程 • 考虑一个Web服务器 • A big process that can do everything itself? • For every client, FORK a new process? • 创建一个进程是有代价的 • Fork a new process to do I/O? • 进程间通信是有代价的 • If Multi-processors, ? • 思路: • 引入“分工合作”的概念 • 在进程内部进一步引入“并发”
可行性: • A task = computation/IO units + resources • Computation/IO units • Are (almost) independent in sense of computation/IO • Should share the process’ address space and other resources • So, separate computation/IO and resources
什么是线程? • 线程:有时又称为轻量级进程 • 是CPU调度的基本单位 • Thread ID + PC + Register Set + stack • 是进程中的一个运行实体 • 同属一个进程的线程之间,共享该进程的 code section, data section, and other resources • Process, a heavyweight process • Traditionally, has only one thread & can do only one task at a time • Now, may contains multiple threads • 资源的拥有者还是进程!
引入线程概念后的应用举例 • 网页浏览器 • 显示图片,文字,放音乐,接收数据,… • 文档编辑器 • 显示、输入、拼写检查
线程与进程的比较 • 调度 • 并发性 • 拥有资源 • 系统开销
引入线程的好处 • Responsiveness • Interactive app. • Resource sharing • 1:N • Economy, when • Create a new …, • E.g., in Solaris, 30 times slower • Context switch, • 5 times slower • Utilization of multiprocessor architectures • Threads of the same process may be running in parallel
引入线程,概念上的一些转变 • 进程基本属性的变化 • 独立性、调度和资源分配的单位 • 切换的变化 • 在同一进程内,线程的切换不会引起进程的切换; • 地址空间上的变化: • 在同一进程内,各线程共享同一地址空间; • 一进程中的线程在另一进程中是不可见的; • 通信手段上的变化: • 同一进程内的线程间的通信主要是基于全局变量进行的;而以同步手段为辅。
User threads VS. Kernel threads 线程的实现方式
多线程的实现模型 • User threads + kernel threads • Three types • N:1(N>1) • 1:1 • N:M(N>=M)
Solaris 2 Threads • User thread + LWP + kernel thread • N(1):1(0):1 • Bound VS. unbound user-level thread • LWP pool for a App. • SMP
回顾 • Benefits • User and Kernel Threads • Multithreading Models
作业 • 阅读参考书,请给出线程的定义。讲明出处。 • 阅读参考书,说明线程概念有几种实现方式?什么是用户态线程,什么是内核态线程?它们之间的对应关系有几种?说明出处。 • 与进程相比,引入线程主要有哪些好处? • 无上机作业