threads 线程

33
Threads 线线 线线线线线线线线 WEB 线线线 线线线线线线线线线线 线线线线线线线线线线线线 线线线线线线 ( 线线线线线 ) 线线 ( 线线线线线 ) 线 CPU 线线线 线线线线线

Upload: maurizio-noonan

Post on 03-Jan-2016

177 views

Category:

Documents


0 download

DESCRIPTION

Threads 线程. 为什么要引入线程 WEB 服务器 同时处理多个客户请求 创建多个进程降低响应时间 进程开销较大 ( 上下文切换 ) 线程 ( 轻量级进程 ) 是 CPU 调度的一个基本单位. 多线程与单线程. 多线程 : 操作系统支持在一个进程中有多个执行线程 单线程 : 操作系统不支持线程概念 MS-DOS 支持单用户进程及单线程 传统 UNIX 支持多用户进程但每进程只支持一个线程 现今的操作系统,如 Solaris, Windows, 支持多线程 Solaris: SUN 微系统公司开发的一种网络操作系统. 单线程与多线程. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Threads  线程

Threads 线程

为什么要引入线程 – WEB 服务器 同时处理多个客户请求– 创建多个进程降低响应时间– 进程开销较大 ( 上下文切换 )

线程 ( 轻量级进程 )– 是 CPU 调度的一个基本单位

Page 2: Threads  线程

多线程与单线程

多线程 : 操作系统支持在一个进程中有多个执行线程

单线程 : 操作系统不支持线程概念 MS-DOS 支持单用户进程及单线程 传统 UNIX 支持多用户进程但每进程只支持一个

线程 现今的操作系统,如 Solaris, Windows, 支持多

线程Solaris: SUN 微系统公司开发的一种网络操作系统

Page 3: Threads  线程

单线程与多线程

Page 4: Threads  线程

Threads 线程 线程是“进程中的一条执行路径或线索”,或

“进程中的一个可调度实体” 线程不运行时需要保存线程的上下文信息 线程有自己的执行堆栈 (stack) 及一些其于线程

的局部变量( local variables )分配的静态存储单元

线程能访问其所属进程所拥有的地址空间和资源某线程更改共享的内存变量 , 所有其余线程均可见某线程打开的文件名柄其余线程都可使用

Page 5: Threads  线程

Benefits Responsiveness

– 可以获得快速的用户响应,如在 C/S 模式下, web server 为每个用户连接运行一个线程; RPC 服务器中, RPC 服务进程会开启多个线程服务于每个 RPC request

Resource Sharing– 进程是拥有资源的基本单位( CPU ,地址空间, I/O 资源),

进程中的线程可以共享这些资源 Economy

– 创建线程比创建进程更快,进程内的线程切换( context switch) 比进程更快, solaris 中创建线程比进程快 30 倍,线程切换比进程切换快 5 倍

Utilization of SMP Architectures– 可以充分利用多处理器体系结构,使得一个进程中的线程在不

同的处理器上运行,提高进程执行的并行度

Page 6: Threads  线程

WEB server/Http request

IE

WEBServer

http://…./index.htm

<html>….<img src=1.jpg><img src=2.jpg>…</html>

http://…/1.jpg

http://…/2.jpg

1.jpg data

2.jpg data

Page 7: Threads  线程

FlashGet / eMule /BT

Page 8: Threads  线程

多线程实例

Page 9: Threads  线程

一些应用程序可以分成若干相对独立的部分 [Word 的后台打印 , 拼写检查等 ,IE浏览器 ]

每一部分用一个线程来实现 一个线程阻塞时可调度同一进程的另一个

线程运行而不是切换进程 线程间通信无需内核干预 需要解决进行线程间同步

Application benefits of threads

Page 10: Threads  线程

共享资源产生的不一致问题

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

Page 11: Threads  线程

三种线程状态 : running, ready, blocked

线程无挂起状态 Termination of a process, will

terminates all threads within the process

Threads States( 线程状态 )

Page 12: Threads  线程

User Level Threads(ULT)

内核不关注线程的存在 所有的线程管理由应用程序通过调用 ULT 库实

现 线程间的切换无需内核模式下的特权指令(无

模式转换) 线程调度由特定的应用

程序完成 例子

- POSIX Pthreads- Mach C-threads一种 UNIX的操作系统 ,采用微内核- Solaris threads

Page 13: Threads  线程

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 对线程上下文的保存和恢复

Page 14: Threads  线程

Advantages 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一个进程的两个线程不能同在两个处理器上同时运行

用户级线程的优缺点

Page 15: Threads  线程

Kernel Level Threads(KLT)内核级的线程

内核完成对所有线程的管理 无线程库,但内核供内核线程的编程接口( API ) 内核需要维护进程和线程的上下文信息 线程间的调度由内核完成 调度的基本单位是线程 例子

- Windows 95/98/NT/2000 - Solaris

- Tru64 UNIX- BeOS

处理机

Page 16: Threads  线程

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导致系统性能的下降

内核级的线程

Page 17: Threads  线程

Multithreading Models多线程模式

Many-to-One ( 多对一 )

One-to-One ( 一对一 )

Many-to-Many ( 多对多 )

Page 18: Threads  线程

Many-to-One

Many user-level threads mapped to single kernel thread. (纯用户级线程)

Used on systems that do not supportkernel threads.(常用于不支持内核线程的系统中 )

Page 19: Threads  线程

One-to-One Each user-level thread maps to kernel

thread.(纯核心级线程)

Examples– Windows 95/98/NT/2000– OS/2

Page 20: Threads  线程

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

Page 21: Threads  线程

Many-to-Many Model

Page 22: Threads  线程

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

Page 23: Threads  线程

Pthreads(POSIX thread)

a POSIX standard (IEEE 1003.1c) 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.

Page 24: Threads  线程

#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

Page 25: Threads  线程

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

Page 26: Threads  线程

Solaris Process

Page 27: Threads  线程

Solaris: Lightweight Process States轻型进程的状态

LWP states are independent of ULT states(except for bound ULTs)

时间片或被抢占

派发 唤醒

停止

阻塞的系统调用

唤醒

Page 28: Threads  线程

Solaris: user-level thread states用户级线程的状态

(attached to a LWP)

停止

停止

停止 停止

派发

抢占

唤醒

Page 29: Threads  线程

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(终止 ).

Page 30: Threads  线程

ResourceAvailable资源可用

Unblock/Resume Resource Available解阻塞且资源可用

UnblockResource Not Available解阻塞但资源不可用

Block/阻塞Suspen挂起

Terminate

Switch 转换Pick toRun

选择运行

Preempted 被抢占

Transition Waiting Terminated

Not Runnable

Runnable

Ready

Standby

Running

Windows 2000 thread states

Page 31: Threads  线程

Process IDSecurity DescriptorBase priorityDefault processor affinityQuota limitsExecution timeI/O countersVM operation countersException/debugging portsExit status

Windows 2000 Process Object Attributes

Page 32: Threads  线程

Thread IDThread contextDynamic priorityBase priorityThread processor affinityThread execution timeAlert statusSuspension countImpersonation tokenTermination portThread exit status

Windows 2000 Thread Object Attributes

Page 33: Threads  线程

Also called light-weight thread ( 轻线程 ) 纤程

Invisible( 不可见的 ) to OS, similar to

user-level thread

Win32 APIs for fiber:

CreateFiber, SwitchToFiber, ConverThreadToFiber

Windows NT/2000 fibers