operatingsystem《操作系统》ch06-processsynchroniza.ppt

上传人:牧羊曲112 文档编号:6513287 上传时间:2023-11-08 格式:PPT 页数:65 大小:955KB
返回 下载 相关 举报
operatingsystem《操作系统》ch06-processsynchroniza.ppt_第1页
第1页 / 共65页
operatingsystem《操作系统》ch06-processsynchroniza.ppt_第2页
第2页 / 共65页
operatingsystem《操作系统》ch06-processsynchroniza.ppt_第3页
第3页 / 共65页
operatingsystem《操作系统》ch06-processsynchroniza.ppt_第4页
第4页 / 共65页
operatingsystem《操作系统》ch06-processsynchroniza.ppt_第5页
第5页 / 共65页
点击查看更多>>
资源描述

《operatingsystem《操作系统》ch06-processsynchroniza.ppt》由会员分享,可在线阅读,更多相关《operatingsystem《操作系统》ch06-processsynchroniza.ppt(65页珍藏版)》请在三一办公上搜索。

1、Chapter 6:Process Synchronization,Chapter Objectives,To introduce the critical-section problem,whose solutions can be used to ensure the consistency of shared data.To present both software and hardware solutions of the critical-section problem.To introduce the concept of atomic transaction and descr

2、ibe mechanisms to ensure atomicity.,Content Overview,BackgroundThe Critical-Section ProblemPetersons SolutionSynchronization HardwareSemaphoresClassic Problems of SynchronizationMonitorsSynchronization Examples Atomic Transactions,6.1 Background,Concurrent access to shared data may result in data in

3、consistencyMaintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processesSuppose that we wanted to provide a solution to the consumer-producer problem that fills all the buffers.We can do so by having an integer count that keeps track of the number of full

4、buffers.Initially,count is set to 0.It is incremented by the producer after it produces a new buffer and is decremented by the consumer after it consumes a buffer.,Producer,while(true)/*produce an item and put in nextProduced*/while(count=BUFFER_SIZE);/do nothing buffer in=nextProduced;in=(in+1)%BUF

5、FER_SIZE;count+;,Consumer,while(true)while(count=0);/do nothing nextConsumed=bufferout;out=(out+1)%BUFFER_SIZE;count-;/*consume the item in nextConsumed Count?!?!,Race Condition,count+could be implemented as register1=count register1=register1+1 count=register1count-could be implemented as register2

6、=count register2=register2-1 count=register2Consider this execution interleaving with“count=5”initially:S0:producer execute register1=count register1=5S1:producer execute register1=register1+1 register1=6 S2:consumer execute register2=count register2=5 S3:consumer execute register2=register2-1 regis

7、ter2=4 S4:producer execute count=register1 count=6 S5:consumer execute count=register2 count=4race condition:several processes access and manipulate the same data concurrently and the outcome of the execution depends on the particular order in which the access takes place.,6.2 The Critical-Section P

8、roblem,critical section,in which the process may be changing common variables,updating a table,writing a file,and so on.entry section/exit section,requirement to the solutions,1.Mutual Exclusion-If process Pi is executing in its critical section,then no other processes can be executing in their crit

9、ical sections(waiting while busy)2.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 of the processes that will enter the critical section next cannot be postponed indefinitely(Let it in if empty)3.

10、Bounded Waiting-A bound must exist on the number of times that other processes are allowed to enter their critical sections after a process has made a request to enter its critical section and before that request is granted(limited waiting)Assume that each process executes at a nonzero speed No assu

11、mption concerning relative speed of the N processes,6.3 Petersons Solution,Two processes solutionAssume that the LOAD and STORE instructions are atomic;that is,cannot be interrupted.The two processes share two variables:int turn;Boolean flag2The variable turn indicates whose turn it is to enter the

12、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 for Process Pi Pj,while(true)flagj=TRUE;turn=i;while(flagi REMAINDER SECTION,while(true)flagi=TRUE;turn=j;while(flagj REMAINDER SECTION,Meet

13、the three requirements,6.4 Synchronization Hardware,Many systems provide hardware support for critical section codeUniprocessors could disable interruptsCurrently running code would execute without preemptionGenerally too inefficient on multiprocessor systemsOperating systems using this not broadly

14、scalableModern machines provide special atomic hardware instructionsAtomic=non-interruptableEither test memory word and set valueOr swap contents of two memory words,TestAndSet Instruction,Definition:boolean TestAndSet(boolean*target)boolean rv=*target;*target=TRUE;return rv:,Solution using TestAndS

15、et,Shared boolean variable lock.,initialized to false.Solution:while(true)while(TestAndSet(/remainder section,Swap Instruction,Definition:void Swap(boolean*a,boolean*b)boolean temp=*a;*a=*b;*b=temp:,Solution using Swap,Shared Boolean variable lock initialized to FALSE;Each process has a local Boolea

16、n variable key.Solution:while(true)key=TRUE;while(key=TRUE)Swap(/remainder section Does not satisfy the bounded-waiting requirement.,6.5 Semaphore,Synchronization tool that does not require busy waiting Semaphore S integer variableTwo standard operations modify S:wait()and signal()Originally called

17、P()and V()Less complicatedCan only be accessed via two indivisible(atomic)operationswait(S)while S=0;/no-op S-;signal(S)S+;,Semaphore as General Synchronization Tool,Counting semaphore integer value can range over an unrestricted domainBinary semaphore integer value can range only between 0 and 1;ca

18、n be simpler to implementAlso known as mutex locksCan implement a counting semaphore S as a binary semaphoreProvides mutual exclusionSemaphore S;/initialized to 1 wait(S);Critical Section signal(S);,Semaphore Implementation,The main disadvantage of the semaphore debnition given here is that it requi

19、res busy waiting.Busy waiting wastes CPU cycles.,Semaphore Implementation with no Busy waiting,With each semaphore there is an associated waiting queue.Each entry in a waiting queue has two data items:value(of type integer)pointer to next record in the listTwo operations:block place the process invo

20、king 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.),Implementation of wait:wait(S)value-;if(value 0)add this process to waiting queue block();Implementation of si

21、gnal:Signal(S)value+;if(value=0)remove a process P from the waiting queue wakeup(P);,Deadlock and Starvation,Deadlock two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processesLet S and Q be two semaphores initialized to 1P0P1wait(S);wait(Q);w

22、ait(Q);wait(S);.signal(S);signal(Q);signal(Q);signal(S);Starvation indefinite blocking.A process may never be removed from the semaphore queue in which it is suspended.,6.6 Classical Problems of Synchronization,Bounded-Buffer ProblemReaders and Writers ProblemDining-Philosophers Problem,Bounded-Buff

23、er Problem,N buffers,each can hold one itemSemaphore mutex initialized to the value 1Semaphore full initialized to the value 0Semaphore empty initialized to the value N.,producer,consumer,Bounded Buffer Problem(Cont.),The structure of the producer process while(true)/produce an item wait(empty);wait

24、(mutex);/add the item to the buffer signal(mutex);signal(full);,Bounded Buffer Problem(Cont.),The structure of the consumer process while(true)wait(full);wait(mutex);/remove an item from buffer signal(mutex);signal(empty);/consume the removed item,Readers-Writers Problem,A data set is shared among a

25、 number of concurrent processesReaders only read the data set;they do not perform any updatesWriters can both read and write.Problem allow multiple readers to read at the same time.Only one single writer can access the shared data at the same time.,Readers-Writers Problem(Cont.),Shared DataData setI

26、nteger readcount initialized to 0.Semaphore mutex initialized to 1.Semaphore wrt initialized to 1.The structure of a writer process while(true)wait(wrt);/writing is performed signal(wrt);,Readers-Writers Problem(Cont.),The structure of a reader process while(true)wait(mutex);readcount+;if(readcount=

27、1)wait(wrt);signal(mutex)/reading is performed wait(mutex);readcount-;if(readcount=0)signal(wrt);signal(mutex);Starvation?!,Dining-Philosophers Problem,Shared data Bowl of rice(data set)Semaphore chopstick 5 initialized to 1,Dining-Philosophers Problem(Cont.),The structure of Philosopher i:While(tru

28、e)wait(chopsticki);wait(chopStick(i+1)%5);/eat signal(chopsticki);signal(chopstick(i+1)%5);/think,Deadlock?!Starvation?!,Problems with Semaphores,Incorrect use of semaphore operations:signal(mutex).wait(mutex)wait(mutex)wait(mutex)Omitting of wait(mutex)or signal(mutex)(or both),*6.7 Monitors,A high

29、-level abstraction that provides a convenient and effective mechanism for process synchronizationOnly one process may be active within the monitor at a timemonitor monitor-name/shared variable declarationsprocedure P1().procedure Pn()Initialization code(.),Schematic view of a Monitor,Condition Varia

30、bles,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()(different from the signal operation of Semaphore),Monitor with Condition Variables,Solution to Dining Philosophers,monit

31、or DP enum THINKING;HUNGRY,EATING)state 5;condition self 5;void pickup(int i)statei=HUNGRY;test(i);if(statei!=EATING)self i.wait;void putdown(int i)statei=THINKING;/test left and right neighbors test(i+4)%5);test(i+1)%5);,void test(int i)if(state(i+4)%5!=EATING),Solution to Dining Philosophers(cont)

32、,void test(int i)if(state(i+4)%5!=EATING),Solution to Dining Philosophers(cont),Each philosopher I invokes the operations pickup()and putdown()in the following sequence:dp.pickup(i)EAT dp.putdown(i),Monitor Implementation Using Semaphores,Variables semaphore mutex;/(initially=1)semaphore next;/(init

33、ially=0)int next-count=0;Each 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-count=0;The operation x.wai

34、t can be implemented as:x-count+;if(next-count 0)signal(next);elsesignal(mutex);wait(x-sem);x-count-;,The operation x.signal can be implemented as:if(x-count 0)next-count+;signal(x-sem);wait(next);next-count-;,Monitor Implementation,The operation x.signal can be implemented as:if(x-count 0)next-coun

35、t+;signal(x-sem);wait(next);next-count-;,6.8 Synchronization Examples,SolarisWindows XPLinuxPthreads,Solaris Synchronization,Implements a variety of locks to support multitasking,multithreading(including real-time threads),and multiprocessingUses adaptive mutexes for efficiency when protecting data

36、from short code segmentsUses condition variables and readers-writers locks when longer sections of code need access to dataUses turnstiles to order the list of threads waiting to acquire either an adaptive mutex or reader-writer lock,Windows XP Synchronization,Uses interrupt masks to protect access

37、to global resources on uniprocessor systemsUses spinlocks on multiprocessor systemsAlso provides dispatcher objects which may act as either mutexes and semaphoresDispatcher objects may also provide eventsAn event acts much like a condition variable,Linux Synchronization,Linux:disables interrupts to

38、implement short critical sectionsLinux provides:semaphoresspin locks,Pthreads Synchronization,Pthreads API is OS-independentIt provides:mutex lockscondition variablesNon-portable extensions include:read-write locksspin locks,6.9 Atomic Transactions,System ModelLog-based RecoveryCheckpointsConcurrent

39、 Atomic Transactions,System Model,Assures that operations happen as a single logical unit of work,in its entirety,or not at allRelated to field of database systemsChallenge is assuring atomicity despite computer system failuresTransaction-collection of instructions or operations that performs single

40、 logical functionHere we are concerned with changes to stable storage diskTransaction is series of read and write operationsTerminated by commit(transaction successful)or abort(transaction failed)operationAborted transaction must be rolled back to undo any changes it performed,Types of Storage Media

41、,Volatile storage information stored here does not survive system crashesExample:main memory,cacheNonvolatile storage Information usually survives crashesExample:disk and tapeStable storage Information never lostNot actually possible,so approximated via replication or RAID to devices with independen

42、t 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 modifications by a transactionMost common is write-ahead loggingLog on stable storage,each log record describes singl

43、e transaction write operation,includingTransaction nameData item nameOld valueNew value written to log when transaction Ti starts written when Ti commitsLog entry must reach stable storage before operation on data occurs,Log-Based Recovery Algorithm,Using the log,system can handle any volatile memor

44、y errorsUndo(Ti)restores value of all data updated by TiRedo(Ti)sets values of all data in transaction Ti to new valuesUndo(Ti)and redo(Ti)must be idempotentMultiple executions must have the same result as one executionIf system fails,restore state of all updated data via logIf log contains without,

45、undo(Ti)If log contains and,redo(Ti),Checkpoints,Log could become long,and recovery could take longCheckpoints shorten log and recovery time.Checkpoint scheme:Output all log records currently in volatile storage to stable storageOutput all modified data from volatile to stable storageOutput a log re

46、cord to the log on stable storageNow recovery only includes Ti,such that Ti started executing before the most recent checkpoint,and all transactions after Ti All other transactions already on stable storage,Concurrent Transactions,Must be equivalent to serial execution serializabilityCould perform a

47、ll transactions in critical sectionInefficient,too restrictiveConcurrency-control algorithms provide serializability,Serializability,Consider two data items A and BConsider Transactions T0 and T1Execute T0,T1 atomicallyExecution sequence called scheduleAtomically executed transaction order called se

48、rial scheduleFor N transactions,there are N!valid serial schedules,Schedule 1:T0 then T1,Nonserial Schedule,Nonserial schedule allows overlapped executeResulting execution not necessarily incorrectConsider schedule S,operations Oi,OjConflict if access same data item,with at least one writeIf Oi,Oj c

49、onsecutive and operations of different transactions&Oi and Oj dont conflictThen S with swapped order Oj Oi equivalent to SIf S can become S via swapping nonconflicting operationsS is conflict serializable,Schedule 2:Concurrent Serializable Schedule,Locking Protocol,Ensure serializability by associat

50、ing lock with each data itemFollow locking protocol for access controlLocksShared Ti has shared-mode lock(S)on item Q,Ti can read Q but not write QExclusive Ti has exclusive-mode lock(X)on Q,Ti can read and write QRequire every transaction on item Q acquire appropriate lockIf lock already held,new r

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号