ImageVerifierCode 换一换
格式:PPT , 页数:63 ,大小:1.65MB ,
资源ID:3317785      下载积分:20 金币
快捷下载
登录下载
邮箱/手机:
温馨提示:
快捷下载时,用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)。 如填写123,账号就是123,密码也是123。
特别说明:
请自助下载,系统不会自动发送文件的哦; 如果您已付费,想二次下载,请登录后访问:我的下载记录
支付方式: 支付宝    微信支付   
验证码:   换一换

加入VIP,免费下载
 

温馨提示:由于个人手机设置不同,如果发现不能下载,请复制以下地址【https://www.docduoduo.com/d-3317785.html】到电脑端继续下载(重复下载不扣费)。

已注册用户请登录:
账号:
密码:
验证码:   换一换
  忘记密码?
三方登录: 微信登录   QQ登录   微博登录 

下载须知

1: 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。
2: 试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。
3: 文件的所有权益归上传用户所有。
4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
5. 本站仅提供交流平台,并不能对任何下载内容负责。
6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

版权提示 | 免责声明

本文(操作系统教程06.ppt)为本站会员(dzzj200808)主动上传,道客多多仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知道客多多(发送邮件至docduoduo@163.com或直接QQ联系客服),我们立即给予删除!

操作系统教程06.ppt

1、Chapter 6: Process Synchronization,Background The Critical-Section Problem Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization Examples Atomic Transactions,Background,Concurrent access to shared data = inconsistency Maintaining data consistency = orderly

2、execution of cooperating processes solution to the consumer-producer problem: integer count = number of full buffers Initially, count is set to 0 incremented by the producer after it produces a new buffer decremented by the consumer after it consumes a buffer,Producer,while (true) /* produce an item

3、 and put in nextProduced */while (count = BUFFER_SIZE); / do nothingbuffer in = nextProduced;in = (in + 1) % BUFFER_SIZE;count+; ,Consumer,while (true) while (count = 0); / do nothingnextConsumed = bufferout;out = (out + 1) % BUFFER_SIZE;count-;/* consume the item in nextConsumed*/,Race Condition,co

4、unt+ could be implemented as register1 = count register1 = register1 + 1 count = register1 count- could be implemented as register2 = count register2 = register2 - 1 count = register2 Consider this execution interleaving with “count = 5” initially:S0: producer execute register1 = count reg1 = 5 S1:

5、producer execute register1 = register1 + 1 reg1 = 6 S2: consumer execute register2 = count reg2 = 5 S3: consumer execute register2 = register2 - 1 reg2 = 4 S4: producer execute count = register1 count = 6 S5: consumer execute count = register2 count = 4,Solution to Critical-Section Problem,Critical

6、section A segment of code, in which the process may be changing common variables, updating a table, writing a file, and so on. Entry section request permission to enter CS Exit section following the CS Remainder section the remaining code 3 requirements to the CS problem: Mutual Exclusion If process

7、 Pi is executing in its critical section, then no other processes can be executing in their critical sections,Solution to Critical-Section Problem,Progress If no process is executing in its critical section and there exist some processes that wish to enter their critical section, then the selection

8、of the processes that will enter the critical section next cannot be postponed indefinitely Bounded Waiting A bound must exist on the number of times that other processes are allowed to enter their critical sections AssumptionAssume each process executes at a nonzero speedNo assumption concerning re

9、lative speed of the n processes,Petersons Solution,2 process solution Assume LOAD The variable turn indicates whose turn it is to enter the critical section. The flag array is used to indicate if a process is ready to enter the critical section flagi = true implies that process Pi is ready,Algorithm

10、 for Process Pi,while (true) flagi = TRUE;turn = j;while ( flagj REMAINDER SECTION,Synchronization Hardware,Many systems provide hardware support for critical section code Uniprocessors disable interrupts Currently running code would execute without preemption Generally too inefficient on multiproce

11、ssor systems Message is passed to all processors, time consuming The clock is kept updated by interrupts Modern machines provide special atomic hardware instructions Either test memory word and set value Or swap contents of two memory words,TestAndSet Instruction,Definition:boolean TestAndSet (boole

12、an *target)boolean rv = *target;*target = TRUE;return rv:,Solution using TestAndSet,Shared boolean variable lock, initialized to false Solution:while (true) while ( TestAndSet (/ remainder section ,Semaphore,Less complicated Do not require busy waiting Semaphore S integer variable Two standard opera

13、tions modify S wait() signal() Originally called: P() from the Dutch proberen, “to test” V() from the Dutch verhogen, “to increment”,Semaphore (cont.),Can only be accessed via two indivisible (atomic) operations wait (S) while S = 0; / no-opS-; signal (S) S+;,Semaphore as General Synchronization Too

14、l,Counting semaphore integer value can range over an unrestricted domain Binary semaphore integer value can range only between 0 and 1 can be simpler to implement Also known as mutex locks Can implement a counting semaphore S as a binary semaphore,Semaphore as General Synchronization Tool,Provides m

15、utual exclusion Semaphore S; / initialized to 1 wait (S);Critical Section signal (S);,Semaphore Implementation with no Busy waiting,Each semaphore is associated with an waiting queue. Each entry in a waiting queue has two data items:value (of type integer)pointer to next record in the list Two opera

16、tions: block place the process invoking the operation on the appropriate waiting queue. wakeup remove one of processes in the waiting queue and place it in the ready queue.,Semaphore Implementation with no Busy waiting (Cont.),Definition of semaphore:typedef struct int value;struct process *list; se

17、maphore; Implementation of wait:wait (semaphore *S) S-value-;if (S-value listblock();,Semaphore Implementation with no Busy waiting (Cont.),Implementation of signal:Signal (semaphore *S) S-value+;if (S-value listwakeup(P); May have negative semaphore values,Deadlock and Starvation,Deadlock two or mo

18、re processes are waiting indefinitely for an event that can be caused by only one of the waiting processes Let S and Q be two semaphores initialized to 1P0 P1wait (S); wait (Q);wait (Q); wait (S);. signal (S); signal (Q);signal (Q); signal (S); Starvation indefinite blocking.,Classic Problems of Syn

19、chronization,Bounded-Buffer Problem Readers and Writers Problem Dining-Philosophers Problem,Bounded-Buffer Problem,N buffers, each can hold one item Semaphore mutex initialized to the value 1 Semaphore full initialized to the value 0 Semaphore empty initialized to the value N.,Bounded Buffer Problem

20、 (Cont.),The structure of the producer processwhile (true) / produce an itemwait (empty);wait (mutex);/ add the item to the buffersignal (mutex);signal (full);,Bounded Buffer Problem (Cont.),The structure of the consumer processwhile (true) wait (full);wait (mutex);/ remove an item from buffersignal

21、 (mutex);signal (empty);/ consume the removed item,Readers-Writers Problem,A data set is shared among a number of concurrent processes Readers only read the data set; they do not perform any updates Writers can both read and write Allow multiple readers to read at the same time Only 1 writer can acc

22、ess the shared data simultaneously,Readers-Writers Problem,Problems 1st readers-writers problem No reader kept waiting unless a writer has already obtained permission to use the shared object i.e., No reader should wait for other readers to finish simply because a writer is waiting 2nd readers-write

23、rs problem Once a writer is ready, that writer performs its write as soon as possible i.e. If a writer is waiting, no new readers may start,Readers-Writers Problem,Starvation 1st case, writers may starve 2nd case, readers may starve Solution to starvation: Shared Data Data set Semaphore mutex =1, en

24、sure readcount is updated Semaphore wrt = 1, Integer readcount initialized to 0.,Readers-Writers Problem (Cont.),The structure of a writer processwhile (true) wait (wrt) ;/ writing is performedsignal (wrt) ;,Readers-Writers Problem (Cont.),The structure of a reader processwhile (true) wait (mutex) ;

25、readcount + ;if (readcount = 1) wait (wrt) ;signal (mutex)/ reading is performedwait (mutex) ;readcount - - ;if (readcount = 0) signal (wrt) ;signal (mutex) ;,Dining-Philosophers Problem,Dining-Philosophers Problem,5 philosophers spend their lives thinking & eating Shared data Bowl of rice (data set

26、) Semaphore chopstick 5 initialized to 1 When a philosopher gets hungry, she tries to pick up 2 chopsticks She may pick up only 1 chopsticks at a time She cant pick up a chopstick in the hand of a neighbor When grabbed 2 chopsticks can she eat After eating, she puts down chopsticks & thinking,Dining

27、-Philosophers Problem (Cont.),The structure of Philosopher i: While (true) wait ( chopsticki );wait ( chopStick (i + 1) % 5 );/ eatsignal ( chopsticki );signal (chopstick (i + 1) % 5 );/ think ,Dining-Philosophers Problem (Cont.),Deadlock (each one pick up a chopstick & wait for the neighbors) Deadl

28、ock prevention: Allow at most 4 philosophers sitting at the table Allow a philosopher to pick up her chopsticks only if both chopsticks are available(she must pick them up in a CS) Asymmetric solution Odd philosopher picks up first her left chopsticks and then her right chopsticks Even philosopher p

29、icks up first her right chopsticks and then her left chopsticks Guard against starvation,Problems with Semaphores,Correct use of semaphore operations: signal (mutex) . wait (mutex) Mutual exclusion violatedwait (mutex) wait (mutex) Deadlock will occurOmitting wait (mutex) or signal (mutex) (or both)

30、 Mutual exclusion violated Deadlock will occur,Monitors,A high-level abstraction for process synchronization Only one active process within the monitor at a time monitor monitor-name / shared variable declarationsprocedure P1 () . procedure Pn () Initialization code ( .) ,Schematic view of a Monitor

31、,Condition Variables,Condition is defined to make monitor powerful condition x, y; Two operations on a condition variable: x.wait () a process that invokes the operation is suspended x.signal () resumes one of processes (if any) that invoked x.wait () Otherwise, nothing happens When P invoke x.signa

32、l() operation, 2 possibilities Signal & wait P waits until Q leaves or waits another condition Signal & continue Q waits until P leaves or waits another condition,Monitor with Condition Variables,Monitor Implementation Using Semaphores,Variables semaphore mutex; / (initially = 1)semaphore next; / (i

33、nitially = 0)int next_count = 0; Each external procedure F will be replaced bywait(mutex); body of F;if (next_count 0)signal(next)else signal(mutex); Mutual exclusion within a monitor is ensured.,Monitor Implementation,For each condition variable x, we have:semaphore x_sem; / (initially = 0)int x_co

34、unt = 0; The operation x.wait can be implemented as:x_count+;if (next_count 0)signal(next);elsesignal(mutex);wait(x_sem);x_count-;,Monitor Implementation,The operation x.signal can be implemented as: if (x_count 0) next_count+;signal(x_sem);wait(next);next_count-;,Synchronization Examples,Windows XP

35、 Linux Pthreads,Windows XP Synchronization,Uses interrupt masks to protect access to global resources on uniprocessor systems Uses spinlocks on multiprocessor systems Also provides dispatcher objects which may act as mutexes, semaphores, events and timers An event acts much like a condition variable

36、 Timers are used to notify thread time expired Dispatcher objects may be in: A signaled state: object is available A nonsignaled state: object is unavailable, thread blocked,Linux Synchronization,Linux provides: semaphores: longer period Spinlocks: On SMP, short duration Enabling & disabling kernel

37、preemption: single-processor,Pthreads Synchronization,Pthreads API is OS-independent It provides: mutex locks condition variables Read-write locks Non-portable extensions include: semaphores spin locks,Atomic Transactions,System Model Log-based Recovery Checkpoints Concurrent Atomic Transactions,Sys

38、tem Model,Assures that operations happen as a single logical unit of work, in its entirety, or not at all Assures atomicity despite computer system failures Transaction - collection of instructions or operations that performs single logical function changes to stable storage disk Transaction is seri

39、es of read and write operations Terminated by commit or abort operation Aborted transaction must be rolled back Related to field of database systems,Types of Storage Media,Volatile storage does not survive system crashes Example: main memory, cache Nonvolatile storage survives crashes Example: disk

40、and tape Stable storage Information never lost approximated via replication or RAID to devices with independent failure modes,Goal is to assure transaction atomicity where failures cause loss of information on volatile storage,Log-Based Recovery,Record to stable storage information about all modific

41、ations by a transaction Most common is write-ahead logging Log on stable storage, each log record describes single transaction write operation, including Transaction name Data item name Old value New valuewritten to log when transaction Ti startswritten when Ti commits Log entry must reach stable st

42、orage before operation on data occurs,Log-Based Recovery Algorithm,Using the log, system can handle any volatile memory errors Undo(Ti) restores value of all data updated by Ti Redo(Ti) sets values of all data in transaction Ti to new values Undo(Ti) and redo(Ti) must be idempotent Multiple executio

43、ns must have the same result as one execution If system fails, restore state of all updated data via log If log contains without , undo(Ti) If log contains and , redo(Ti),Checkpoints,Checkpoints shorten log and recovery time. Checkpoint scheme: Output all log records currently in volatile storage to

44、 stable storage Output all modified data from volatile to stable storage Output a log record to the log on stable storage Now recovery only includes Ti, such that Ti started executing before the most recent checkpoint, and all transactions after Ti,Concurrent Transactions,Must be equivalent to seria

45、l execution serializability Could perform all transactions in critical section Inefficient, too restrictive Concurrency-control algorithms provide serializability,Serializability,Consider two data items A and B Consider Transactions T0 and T1 Execute T0, T1 atomically Execution sequence called sched

46、ule Atomically executed transaction order called serial schedule For N transactions, there are N! valid serial schedules,Schedule 1: T0 then T1,Nonserial Schedule,Nonserial schedule allows overlapped execute Does not necessarily imply an incorrect execution Conflict - Consider schedule S, operations

47、 Oi, Oj if access same data item, with at least one write If Oi, Oj consecutive operations of S, different transactions, Oi and Oj dont conflict Then S with swapped order Oj, Oi equivalent to S If S can become S via swapping nonconflicting operations S is conflict serializable,Schedule 2: Concurrent

48、 Serializable Schedule,Locking Protocol,Ensure serializability by associating lock with each data item Follow locking protocol for access control Locks Shared Ti has shared-mode lock (S) on item Q, Ti can read Q but not write Q Exclusive Ti has exclusive-mode lock (X) on Q, Ti can read and write Q R

49、equire every transaction on item Q acquire appropriate lock If lock already held, new request may have to wait Similar to readers-writers algorithm,Two-phase Locking Protocol,Generally ensures conflict serializability Each transaction issues lock and unlock requests in two phases Growing obtaining locks Shrinking releasing locks Does not prevent deadlock,

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报