1 / 159

Chapter 7: Process Synchronization 进程同步

Chapter 7: Process Synchronization 进程同步. 7.1 Background 背景 7.2 The Critical-Section Problem 临界区问题 7.3 Synchronization Hardware 同步的硬件实现

binah
Download Presentation

Chapter 7: Process Synchronization 进程同步

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 7: Process Synchronization进程同步 • 7.1 Background 背景 • 7.2 The Critical-Section Problem 临界区问题 • 7.3 Synchronization Hardware 同步的硬件实现 • 7.4 Semaphores 信号量 • 7.5 Classical Problems of Synchronization 经典同步问题 • 7.6 Critical Regions 临界区 • 7.7 Monitors 管程 • 7.8 OS Synchronization 操作系统的同步机制 • 7.9 Atomic Transactions原子事务处理 Operating System Concepts

  2. 7.1 Background背景 • Concurrent access to shared data may result in data inconsistency. 对共享数据的并发访问可能导致数据的不一致性 • Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes. 要保持数据的一致性,就需要一种保证并发进程的正确执行顺序的机制 Operating System Concepts

  3. Background (Cont.) • Shared-memory solution to bounded-butter problem (Chapter 4) allows at most n – 1 items in buffer at the same time. A solution, where all N buffers are used is not simple. 第4章中解决有限缓冲区问题的共享内存方法…N项的缓冲器最多只能使用n-1项 • Suppose that we modify the producer-consumer code by adding a variable counter, initialized to 0 and incremented each time a new item is added to the buffer 假定我们通过增加一个计数器变量修改生产者-消费者代码,初始值为 0,在缓冲区增加一个项目(数据)计数器加1 Operating System Concepts

  4. Bounded-Buffer有界缓冲区 • Shared data #define BUFFER_SIZE 10 typedef struct { . . . } item; item buffer[BUFFER_SIZE]; int in = 0; int out = 0; int counter = 0; Operating System Concepts

  5. Bounded-Buffer (Cont.-1) • Producer process item nextProduced; while (1) { while (counter == BUFFER_SIZE) ; /* do nothing */ buffer[in] = nextProduced; in = (in + 1) % BUFFER_SIZE; counter++; } Operating System Concepts

  6. Bounded-Buffer (Cont.-2) • Consumer process item nextConsumed; while (1) { while (counter == 0) ; /* do nothing */ nextConsumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; counter--; } Operating System Concepts

  7. Bounded Buffer (Cont.-3) • The statementscounter++;counter--;must be performed atomically. • Atomic operation means an operation that completes in its entirety without interruption. Operating System Concepts

  8. Bounded Buffer (Cont.-4) • The statement “count++” may be implemented in machine language as:register1 = counter register1 = register1 + 1counter = register1 • The statement “count—” may be implemented as:register2 = counterregister2 = register2 – 1counter = register2 Operating System Concepts

  9. Bounded Buffer (Cont.-5) • If both the producer and consumer attempt to update the buffer concurrently, the assembly language statements may get interleaved. 如果生产者和消费者并发地更新缓冲区,汇编语言语句可以得到的交替存取 • Interleaving depends upon how the producer and consumer processes are scheduled. 交替取决于生产者和消费者进程如何调度 Operating System Concepts

  10. Bounded Buffer (Cont.-6) • Assume counter is initially 5. One interleaving of statements is:producer: register1 = counter (register1 = 5)producer: register1 = register1 + 1 (register1 = 6)consumer: register2 = counter (register2 = 5)consumer: register2 = register2 – 1 (register2 = 4)producer: counter = register1 (counter = 6)consumer: counter = register2 (counter = 4) • The value of count may be either 4 or 6, where the correct result should be 5. Operating System Concepts

  11. Race Condition竞争条件 • Race condition: The situation where several processes access and manipulate shared data concurrently. The final value of the shared data depends upon which process finishes last. Outcome of execution depends on the particular order in which the access takes place. 竞争条件:若干进程并发地访问并且操纵共享数据的情况。 共享数据的值取决于哪个进程最后完成 • To prevent race conditions, concurrent processes must be synchronized. 防止竞争条件,并发进程必须被同步 Operating System Concepts

  12. 7.2 The Critical-Section Problem临界区问题 • n processes all competing to use some shared data 所有n 个进程竞争使用一些共享的数据。 • Each process has a code segment, called critical section, in which the shared data is accessed. 每个进程有一个代码段, 称为临界区, 在那儿共享数据被访问. 临界区:访问临界资源的那段代码 • Problem – ensure that when one process is executing in its critical section, no other process is allowed to execute in its critical section. 问题- 保证当一个进程正在临界区执行时,没有另外的进程进入临界区执行 • 多个进程共享临界资源时必须互斥使用 Operating System Concepts

  13. 临界资源 多道程序环境->进程之间存在资源共享,进程的运行时间受影响 • 进程间资源访问冲突 • 共享变量的修改冲突 • 操作顺序冲突 • 进程间的制约关系 • 间接制约:进行竞争--独占分配到的部分或全部共享资源,“互斥” • 直接制约:进行协作--等待来自其他进程的信息,“同步” • 临界资源:一次只允许一个进程使用(访问)的资源。如:硬件打印机、磁带机等,软件的消息缓冲队列、变量、数组、缓冲区等。 硬件或软件(如外设、共享代码段、共享数据结构),多个进程在对其进行访问时(关键是进行写入或修改),必须互斥地进行--有些共享资源可以同时访问,如只读数据 Operating System Concepts

  14. Solution to Critical-Section Problem must satisfy 解决临界区问题需满足 1.Mutual Exclusion: If process Pi is executing in its critical section, then no other processes can be executing in their critical sections. 互斥:假定进程Pi在其临界区内执行,其他任何进程将被排斥在自己的临界区之外. 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. 有空让进:临界区虽没有进程执行,但有些进程需要进入临界区,不能无限期地延长下一个要进入临界区进程的等待时间. Operating System Concepts

  15. Solution to Critical-Section Problem must satisfy (Cont.) 3. 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. 有限等待: 在一个进程提出进入临界区的请求和该请求得到答复的时间内,其他进程进入临界区前的等待时间必须是有限的. • Assume that each process executes at a nonzero speed 假定每个进程都以非零的的速率执行. • No assumption concerning relative speed of the n processes. 没有任何关于这n个进程相对执行速率的假定 Operating System Concepts

  16. 同步机制应遵循的准则 • 空闲让进。 当无进程进入临界区时,相应的临界资源处于空闲状态,因而允许一个请求进入临界区的进程立即进入自己的临界区。 • 忙则等待(互斥)。 当已有进程进入自己的临界区时,即相应的临界资源正被访问,因而其它试图进入临界区的进程必须等待,以保证进程互斥地访问临界资源。 • 有限等待。 对要求访问临界资源的进程,应保证进程能在有限时间进入临界区,以免陷入“饥饿”状态。 • 让权等待。 当进程不能进入自己的临界区时,应立即释放处理机,以免进程陷入忙等。 Operating System Concepts

  17. 解释: 使用临界区的原则 • 每次只允许一个进程处于它的临界区(CS)中 • 若有多个进程同时想进入CS,应在有限时间内让其中一个进程进入CS,以免阻塞 • 进程在CS内只能逗留有限时间 • 不应使要进入CS的进程无限期地等待在CS之外 • 在CS之外的进程不可以阻止其他进程进入CS • 不要预期和假定进程进展的相对速度以及可用的处理器数目. 因为这是不可预期的. Operating System Concepts

  18. Fig 7.1 General structure of a typical process Pi • General structure of process Pi(other process Pj) do { entry section进入区 critical section临界区 exit section退出区 reminder section剩余区 } while (1); • 临界区(critical section):进程中访问临界资源的一段代码。 • 进入区(entry section):在进入临界区之前,检查可否进入临界区的一段代码。如果可以进入临界区,通常设置相应"正在访问临界区"标志 • 退出区(exit section):用于将"正在访问临界区"标志清除。 • 剩余区(remainder section):代码中的其余部分。 • Processes may share some common variables to synchronize their actions. Operating System Concepts

  19. 7.2.1 Two-Process SolutionsAlgorithm 1 (软件方法) • Only 2 processes, P0 and P1 • Shared variables: • int turn;initially turn = 0 • turn = i  Pi can enter its critical section ( j=1-i) • Process Pi do { while (turn != i) ; critical section turn = j; reminder section } while (1); • Satisfies mutual exclusion, but not progress(不满足有空让进条件) Operating System Concepts

  20. 问题: • 必须轮流使用临界区 • 如果一个进程失败,另一个进程将被永久阻塞 • 缺点:强制轮流进入临界区,没有考虑进程的实际需要。容易造成资源利用不充分:在Pi出让临界区之后,Pj使用临界区之前,Pi不可能再次使用临界区; Operating System Concepts

  21. 7.2.1.2 Algorithm 2 • Shared variables • boolean flag[2];initially flag [0] = flag [1] = false. • flag [i] = true  Pi ready to enter its critical section • Process Pi do { flag[i] := true; while (flag[j]) ; critical section flag [i] = false; remainder section } while (1); • Satisfies mutual exclusion, but not progress requirement (see next page). Operating System Concepts

  22. 7.2.1.2 Algorithm 2 • not progress requirement: if 两个进程在执行while语句前, 同时执行了: T0: P0 sets flag[0] := true T1: P1 sets flag[1] := true then P0 and P1 are looping forever in their respective while statements! • 也即: Pi和Pj可能都进入不了临界区。当 Pi执行了flag[i] := true后,Pj执行了flag[j] := true,这样两个进程都无法进入临界区 Operating System Concepts

  23. Algorithm 2-1 • Shared variables • boolean flag[2];initially flag [0] = flag [1] = false. • flag [i] = true  Pi enter its critical section • Process Pi do { while (flag[j]) ; { flag[i] := true; critical section} flag [i] = false; remainder section } while (1); • Satisfies mutual exclusion, but not progress requirement. • Pi和Pj可能同时进入临界区。当 Pi执行了while (flag[j])后,Pj执行while (flag[i]) ,这样两个进程同时进入了临界区 Operating System Concepts

  24. 7.2.1.3 Algorithm 3 • Combined shared variables of algorithms 1 and 2. • Process Pi do { flag [i]:= true; turn = j; while (flag [j] and turn = j) ; critical section flag [i] = false; remainder section } while (1); • Meets all three requirements; solves the critical-section problem for two processes. Operating System Concepts

  25. Algorithm 3 • 结合算法1和算法2,是正确的算法 • turn=j;描述可进入的进程(同时修改标志时) • 在进入区先修改后检查,并检查并发修改的先后: • 检查对方flag,如果不在临界区则自己进入--空闲则入 • 否则再检查turn:保存的是较晚的一次赋值,则较晚的进程等待,较早的进程进入--先到先入,后到等待 Operating System Concepts

  26. 7.2.1.3 Algorithm 3 • To prove “Mutual exclusion” property (That is Pi and Pj can’t be in CS at same time) • Pi enter CS only if flag[j]==false or turn==i • turn = 0 or 1, but cannot be both • … • To prove “Progress” property • Pi is in while statements only when flag[j]==true and turn==j • Then if Pj is not ready to enter CS, flag[j]==false • if Pj ready to enter CS, flag[j]==true, but turn=i or j , so Pi or Pj can enter • To prove “Bounded-waiting” property • If Pj exit its CS, flag[j]=false, then Pi can enter its CS Operating System Concepts

  27. Dekker算法 – 7.4题 var boolean flag[2] ; flag[0]=flag[1]=false; int turn; turn=0/1; Pi:do { flag[i]=true; while flag[j] { if turn=j { flag[i]=false; while turn=j ; flag[i]=true; } } Critical Section i 请证明:这个算法是否满足临界区 turn=j; 问题的三个条件 flag[i]=false; Remainder Section }while(1); Operating System Concepts

  28. 7.2.2 Multiple-Process Solutions Bakery Algorithm (面包房算法) Algorithm of solving the Critical section for n processes • Before entering its critical section, process receives a number. Holder of the smallest number enters the critical section. 在进入临界区前,进程接收一个数字,最小数字的持有者进入临界区 • If processes Pi and Pj receive the same number, if i < j, then Pi is served first; else Pj is served first. • The numbering scheme always generates numbers in increasing order of enumeration; i.e., 1,2,3,3,3,3,4,5... Operating System Concepts

  29. Bakery Algorithm • Define the following Notation order : (a,b) -- (ticket #, process id #) • (a,b) < (c,d) if a < c or if a = c and b < d • max (a0,…, an-1) is a number, k such that k ai for i = 0, …, n – 1 • Shared data boolean choosing[n]; int number[n]; Data structures are initialized to false and 0 respectively Operating System Concepts

  30. Fig 7.5 The structure of process Pi in the Bakery Algorithm 取一个编号(在原有编号基础上+1) do { choosing[i] = true; number[i] = max(number[0], number[1], …, number [n – 1])+1; choosing[i] = false; for (j = 0; j < n; j++) { while (choosing[ j]) ; while ((number[ j] != 0) &&((number[ j],j) < (number[i],i))) ; } critical section number[i] = 0; remainder section } while (1); Pj正在取编号 有j欲进入CS且Pj的编号<Pi ,或者Pi 和Pj同时拿到相同编号但j<i 此时Pi拥有最小的number[i] Operating System Concepts

  31. 实现进程同步的方式 • Critical-section (软件方法) • Synchronization hardware (硬件方法) • Semaphores (信号量方法) Operating System Concepts

  32. 7.3 Synchronization Hardware同步的硬件实现 (硬件方法) • Hardware features can make the programming task easier and improve system efficiency. • Hardware instruction: Test and modify the content of a word atomically. boolean TestAndSet(boolean &target) { boolean rv = target; target = true; return rv; } Operating System Concepts

  33. Mutual Exclusion with Test-and-Set • Shared data: boolean lock = false; • Process Pi do { while (TestAndSet(lock)) ; critical section lock = false; remainder section }while(1); • 利用TestAndSet实现进程互斥:每个临界资源设置一个公共布尔变量lock,初值为FALSE • 在进入区利用TS进行检查:有进程在临界区时,重复检查;直到其它进程退出时,检查通过; Operating System Concepts

  34. The definition of Swap instruction • Atomically swap two variables. void Swap(boolean &a, boolean &b) { boolean temp = a; a = b; b = temp; } Operating System Concepts

  35. Mutual Exclusion with Swap • Shared data (initialized to false): boolean lock; /* (a global variable) • Process Pi do { key = true; /* ( a local variable) while (key == true) Swap(lock,key); critical section lock = false; remainder section } while (1); • Don’t satisfy the bounded-waiting requirement (when Pi,Pj execute “key=true” at same time) Operating System Concepts

  36. Fig 7.10 Bounded-waiting mutual exclusion with TestAndSet waiting[i]=false 意味着另一个进程从CS退出,并将Pi设置为可进入 Boolean waiting[n], lock ; global variables, to be initialize to false Do { waiting[i]=true; key= true; while ( waiting[i] && key ) key=TestAndSet(lock); waiting[i]=false; critical section; j= (i+1) % n ; while ((j != i) && !waiting[ j ]) j= (j+1) % n ; if (j == i) lock = false ; else waiting[ j ] = false ; remainder section ; }while(1) Key=false 意味着已经没有一个进程处于CS 寻找下一个正在等待进入CS的进程 已经没有正在等待进入CS的进程 将Pj选为下一个可进入CS的进程 Operating System Concepts

  37. Bounded-waiting mutual exclusion with TestAndSet • This algorithm satisfies all the critical section requirement . • To prove that the mutual-exclusion(互斥条件)requirement • Pi 可以进入CS只有在 waiting[i]== false 或 key == false时 • 只有在执行了 TestAndSet后,key 才可能变为 false;而且只有第一个执行了 TestAndSet 的进程,才能得到 key== false,其它进程必须等待 • 只有在一个进程离开CS时才会有一个(且最多仅有一个)进程的waiting[i] 由true变为false • 从而确保满足互斥条件 Operating System Concepts

  38. Bounded-waiting mutual exclusion with TestAndSet • To prove that the progress(有空让进条件)requirement (see p.200) • 任何一个已经进入CS的进程在“exit section” 时,设置:lock =false 或 waiting[ j ]= false,确保了至少可以让一个进程进入CS • To prove that the bounded-waiting(有限等待条件)requirement (see p.200) • 任何一个已经进入CS的进程Pi在“exit section” 时,将会依次扫描waiting 数组(i+1,i+2,…n-1,0,…i-1),并仅将Pi后面最先找到的进程j的waiting[ j]设置为false • 这就使进程能依此循环进入CS Operating System Concepts

  39. 硬件方法的优点 • 适用于任意数目的进程,在单处理器或多处理器上 • 简单,容易验证其正确性 • 可以支持进程内存在多个临界区,只需为每个临界区设立一个布尔变量 • 硬件方法的缺点 • 等待要耗费CPU时间,不能实现"让权等待" • 可能"饥饿":从等待进程中随机选择一个进入临界区,有的进程可能一直选不上 • 可能死锁 Operating System Concepts

  40. 7.4 Semaphores信号量--1965年由Dijkstra提出 • 软件和硬件方法解决互斥问题的缺陷: • 软件:算法太复杂,效率不高 • 中断屏蔽方法:只能用于单机系统 • 硬件指令:忙等待 • 1965年,荷兰学者Dijkstra提出的信号量机制是一种卓有成效的进程同步工具。在长期广泛的应用中,信号量机制又得到了很大的发展,它从整型信号量机制发展到记录型信号量机制,进而发展为“信号集”机制。现在信号量机制已广泛应用于OS中。 • Synchronization tool that does not require busy waiting.一种不需要忙等待的同步工具. • Semaphore S – integer variable信号量S – 整型变量 • 解决N个进程的同步互斥问题 Operating System Concepts

  41. 每个信号量s除一个整数值s.value(计数)外,还有一个进程等待队列s.L,其中是阻塞在该信号量的各个进程的标识每个信号量s除一个整数值s.value(计数)外,还有一个进程等待队列s.L,其中是阻塞在该信号量的各个进程的标识 • 信号量只能通过初始化和两个标准的原语来访问--作为OS核心代码执行,不受进程调度的打断 • 初始化指定一个非负整数值,表示空闲资源总数(又称为"资源信号量")--若为非负值表示当前的空闲资源数,若为负值其绝对值表示当前等待临界区的进程数 • “二值信号量(binary semaphore)":只允许信号量取0或1值 Operating System Concepts

  42. 7.4.1 整型信号量 • Semaphore S – integer variable信号量S – 整型变量 • can only be accessed via two indivisible (atomic) operations 仅能通过两个不可分割的[原子]操作访问 wait (S): ( P-操作 ) while S 0 do no-op;S--; signal (S): ( V-操作) S++; Operating System Concepts

  43. Fig 7.11 Multual-exclusion with semaphores • Shared data: semaphore mutex; //initially mutex = 1 • Process Pi: do { wait(mutex); critical section signal(mutex); remainder section} while (1); Operating System Concepts

  44. 7.4.2 记录型信号量 • To overcome the problem of “busy waiting” • Define a semaphore as a record typedef struct { int value; struct process *L; } semaphore; • Assume two simple operations: • block suspends the process that invokes it. • wakeup(P) resumes the execution of a blocked process P. Operating System Concepts

  45. Implementation • Semaphore operations now defined as wait(S) : S.value--; if (S.value < 0) { add this process to S.L; block; }signal(S) : S.value++; if (S.value <= 0) { remove a process P from S.L; wakeup(P); } • value 是负数,表示处于阻塞状态的进程数 Operating System Concepts

  46. wait、signal操作讨论 • 信号量的物理含义 S.value >0 表示有S个资源可用; S.value=0 表示无资源可用或表示不允许进程再进入临界区; S.value<0 则|S.value|表示在等待队列中进程的个数或表示等待进入临界区的进程个数。 wait(S):表示申请一个资源;signal(S)表示释放一个资源。 Operating System Concepts

  47. wait、signal操作讨论 • wait、signal操作必须成对出现,有一个wait操作就一定有一个signal操作。当为互斥操作时,它们同处于同一进程。当为同步操作时,则不在同一进程中出现。 • 如果两个wait操作相邻,那么它们的顺序至关重要,而两个相邻的signal操作的顺序无关紧要。一个同步wait操作与一个互斥wait操作在一起时,同步wait操作在互斥wait操作前。 • wait、signal操作的优缺点: 优点:简单,而且表达能力强(用wait、signal操作可解决任何同步互斥问题。) 缺点:不够安全;wait、signal操作使用不当会出现死锁;实现复杂。 Operating System Concepts

  48. Semaphore as a General Synchronization Tool • Execute B in Pj only after A executed in Pi • Use semaphore flag initialized to 0 • Code: Pi Pj … … Await(flag) signal(flag) B … … Operating System Concepts

  49. 同步原语的不可分割性 • 含义: • 保证进程间互斥地使用同步原语 • 整体操作,不可分割 • 实现方法: • 用软件的互斥算法,用开关中断保证整体性 • 不是好的解决方法 • 用硬件开关中断实现互斥和完整性 • 仅适用于单处理机系统 • 用硬件指令方法在多处理机中实现互斥 • 用硬件和固件直接实现同步原语 Operating System Concepts

  50. 同步原语的不可分割性 • 实例: 用硬件指令实现互斥使用的同步原语 Wait(S): While TS(lock) do skip; /* 上锁 While S<=0 do skip; /* 同步原语代码 S:=S-1; lock :=false ; /* 开锁 Signal(S): While TS(lock) do skip; /* 上锁 S:=S+1 /* 同步原语代码 lock :=false ; /* 开锁 Operating System Concepts

More Related