Presentation is loading. Please wait.

Presentation is loading. Please wait.

Threads 线程 为什么要引入线程 线程(轻量级进程) WEB服务器 同时处理多个客户请求 创建多个进程降低响应时间

Similar presentations


Presentation on theme: "Threads 线程 为什么要引入线程 线程(轻量级进程) WEB服务器 同时处理多个客户请求 创建多个进程降低响应时间"— Presentation transcript:

1 Threads 线程 为什么要引入线程 线程(轻量级进程) WEB服务器 同时处理多个客户请求 创建多个进程降低响应时间
进程开销较大(上下文切换) 线程(轻量级进程) 是CPU调度的一个基本单位

2 多线程与单线程 多线程: 操作系统支持在一个进程中有多个执行线程 单线程: 操作系统不支持线程概念 MS-DOS 支持单用户进程及单线程
传统 UNIX支持多用户进程但每进程只支持一个线程 现今的操作系统,如Solaris, Windows, 支持多线程 Solaris: SUN微系统公司开发的一种网络操作系统

3 单线程与多线程

4 Threads 线程 线程是“进程中的一条执行路径或线索”,或“进程中的一个可调度实体” 线程不运行时需要保存线程的上下文信息
线程有自己的执行堆栈(stack)及一些其于线程的局部变量(local variables)分配的静态存储单元 线程能访问其所属进程所拥有的地址空间和资源 某线程更改共享的内存变量,所有其余线程均可见 某线程打开的文件名柄其余线程都可使用

5 Benefits Responsiveness Resource Sharing Economy
可以获得快速的用户响应,如在C/S模式下,web server为每个用户连接运行一个线程;RPC服务器中,RPC服务进程会开启多个线程服务于每个RPC request Resource Sharing 进程是拥有资源的基本单位(CPU,地址空间,I/O资源),进程中的线程可以共享这些资源 Economy 创建线程比创建进程更快,进程内的线程切换(context switch)比进程更快,solaris中创建线程比进程快30倍,线程切换比进程切换快5倍 Utilization of SMP Architectures 可以充分利用多处理器体系结构,使得一个进程中的线程在不同的处理器上运行,提高进程执行的并行度

6 WEB server/Http request
IE <html>….<img src=1.jpg><img src=2.jpg>…</html> 1.jpg data 2.jpg data

7 FlashGet / eMule /BT

8 多线程实例

9 Application benefits of threads
一些应用程序可以分成若干相对独立的部分[Word 的后台打印,拼写检查等,IE浏览器] 每一部分用一个线程来实现 一个线程阻塞时可调度同一进程的另一个线程运行而不是切换进程 线程间通信无需内核干预 需要解决进行线程间同步 Consider an application that consists of several independent parts that do not need to run in sequence(一些应用程序可以分成若干相对独立的部分)[Word 的后台打印,拼写检查等,IE浏览器] Each part can be implemented as a thread(每一部分用一个线程来实现) Whenever one thread is blocked waiting for an I/O, execution could possibly switch to another thread of the same application (instead of switching to another process) Since threads within the same process share memory and files, they can communicate with each other without invoking the kernel (线程间通信无需内核干预) Therefore necessary to synchronize the activities of various threads so that they do not obtain inconsistent views of the data(需要进行线程间同步)

10 共享资源产生的不一致问题 3 个变量: A, B, C 由 T1和T2两个线程共享 T1 计算 C = A+B
T2 从 A 转X至 B(转帐) T2 : A = A -X and B = B+X (so that A+B is unchanged) If T1 computes A+B after T2 has done A = A-X but before B = B+X, then T1 will not obtain the correct result for C = A + B

11 Threads States(线程状态) 三种线程状态: running, ready, blocked 线程无挂起状态 Termination of a process, will terminates all threads within the process

12 User Level Threads(ULT)
内核不关注线程的存在 所有的线程管理由应用程序通过调用ULT库实现 线程间的切换无需内核模式下的特权指令(无模式转换) 线程调度由特定的应用 程序完成 例子 - POSIX Pthreads - Mach C-threads 一种UNIX的操作系统,采用微内核 - Solaris threads

13 User Level Threads library 用户级线程库
Contains codes for: (包含以下代码) creating and destroying threads(线程的创建和撤消) passing messages and data between threads 线程间数据和消息的传递 scheduling thread execution 对线程的调度 saving and restoring thread contexts 对线程上下文的保存和恢复

14 用户级线程的优缺点 Advantages Inconveniences
Thread switching does not involve the kernel: no mode switching 无模式(管态/目态)转换 Scheduling can be application specific: choose the best algorithm. 可选择最好的调度算法 ULTs can run on any OS. Only needs a thread library 只要有库,就可在任何操作系统运行 Inconveniences Most system calls are blocking and the kernel blocks processes. So all threads within the process will be blocked 多数的系统调用将阻塞该进程的所有线程 The kernel can only assign processes to processors. Two threads within the same process cannot run simultaneously on two processors 一个进程的两个线程不能同在两个处理器上同时运行

15 Kernel Level Threads(KLT) 内核级的线程
内核完成对所有线程的管理 无线程库,但内核供内核线程的编程接口(API) 内核需要维护进程和线程的上下文信息 线程间的调度由内核完成 调度的基本单位是线程 例子 - Windows 95/98/NT/2000 - Solaris - Tru64 UNIX - BeOS 处理机

16 内核级的线程 Inconveniences Advantages
the kernel can simultaneously schedule many threads of the same process on many processors 内核可在多处理机上同时对一个进程的多个线程进行调度 blocking is done on a thread level 阻塞仅限线程级别 kernel routines can be multithreaded 内核程序也可以是多线程 Inconveniences thread switching within the same process involves the kernel. We have 2 mode switches per thread switch 同进程的线程内的转换涉及内核,每一个线程的转换需要两个模式转换 this results in a significant performance slowing down 导致系统性能的下降

17 Multithreading Models 多线程模式
Many-to-One (多对一) One-to-One (一对一) Many-to-Many (多对多)

18 Many-to-One Many user-level threads mapped to single kernel thread.(纯用户级线程) Used on systems that do not support kernel threads.(常用 于不支持内核线程的 系统中)

19 One-to-One Each user-level thread maps to kernel thread. (纯核心级线程)
Examples Windows 95/98/NT/2000 OS/2

20 Many-to-Many Model 混合式线程
Allows many user level threads to be mapped to many kernel threads. Takes advantage of many-to-one and one-to-one models Allows the operating system to create a sufficient(充足的) number of kernel threads. 例子 Solaris 2 Windows NT/2000 with the ThreadFiber纤程package

21 Many-to-Many Model

22 Thread pools (线程池) - avoid too many threads from exhausting system resources(CPU,memory,etc.) 避免过多的线程耗尽系统资源 - a pool of threads is created in advance to sit and wait for work (在线程池中预先创建一些线程并等待任务) - faster to service a request with an existing thread than waiting to create one. 已存在的线程比新创建的线程能更快地响应请求 - number of threads is limited. - example: multi-threaded server architecture in database management systems. 数据库管理系统中的多线程服务架构 Thread specific data 线程的特定数据 - a thread might need to own its private data

23 Pthreads(POSIX thread)
a POSIX standard (IEEE c) API for thread creation and synchronization. API specifies behavior of the thread library, implementation is up to development of the library. Common in UNIX operating systems.

24 1+2+3+….+n #include <pthread.h> #include <stdio.h>
int sum; void *runner(void *param); main(int argc, char *argv[]) { ptread_t id; pthread_attr_t attr; pthread_attr_init(&attr); //初始化线程属性为缺省属性 pthread_create(&tid,&attr,runner,argv[1]); //创建线程 pthread_join(tid,NULL); //等待线程tid结束 printf(“sum=%d\n”,sum); } void *runner(void *param) int upper=atoi(param); int i; sum = 0; if (upper >0) for ( i = 1; i <=upper; i++) sum +=i; pthread_exit(0); 1+2+3+….+n

25 Solaris 2 Threads Solaris: SUN的一个网络操作系统

26 Solaris Process

27 Solaris: Lightweight Process States 轻型进程的状态
停止 时间片或被抢占 唤醒 派发 阻塞的系统调用 唤醒 LWP states are independent of ULT states (except for bound ULTs)

28 Solaris: user-level thread states 用户级线程的状态
停止 唤醒 停止 抢占 派发 停止 停止 (attached to a LWP)

29 Windows 2000 Threads Windows 2000 processes and threads are all implemented as objects. 均用对象的方式实现 Implements the one-to-one mapping. 一对一模式 basic thread components 基本的线程组件 - a thread id - register set - separate user and kernel stacks 用户栈与内核栈分离 - private data storage area(local variables) 私有数据存储区 A thread can be one of six states: ready(就绪), standby(备用), running(运行), waiting(等待), transition(转换), terminated(终止).

30 Windows 2000 thread states Runnable Not Runnable Standby Ready Running
Pick to Run 选择运行 Switch 转换 Preempted 被抢占 Ready Running Resource Available 资源可用 Unblock/Resume Resource Available 解阻塞且资源可用 Terminate Block/阻塞 Suspen挂起 Transition Waiting Terminated Unblock Resource Not Available 解阻塞但资源不可用 Not Runnable

31 Windows 2000 Process Object Attributes
Process ID Security Descriptor Base priority Default processor affinity Quota limits Execution time I/O counters VM operation counters Exception/debugging ports Exit status

32 Windows 2000 Thread Object Attributes
Thread ID Thread context Dynamic priority Base priority Thread processor affinity Thread execution time Alert status Suspension count Impersonation token Termination port Thread exit status

33 Windows NT/2000 fibers Also called light-weight thread (轻线程) 纤程
Invisible(不可见的) to OS, similar to user-level thread Win32 APIs for fiber: CreateFiber, SwitchToFiber, ConverThreadToFiber


Download ppt "Threads 线程 为什么要引入线程 线程(轻量级进程) WEB服务器 同时处理多个客户请求 创建多个进程降低响应时间"

Similar presentations


Ads by Google