600 likes | 780 Views
Chapter 6: Process Synchronization. Module 6: Process Synchronization. Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors. Background.
E N D
Module 6: Process Synchronization • Background • The Critical-Section Problem • Peterson’s Solution • Synchronization Hardware • Semaphores • Classic Problems of Synchronization • Monitors
Background • Concurrent access to shared data may result in data inconsistency • Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes • Suppose 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 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. P191
Producer while (true) { /* produce an item and put in nextProduced */ while (count == BUFFER_SIZE) ; // do nothing buffer [in] = nextProduced; in = (in + 1) % BUFFER_SIZE; count++; }
Consumer while (true) { while (count == 0) ; // do nothing nextConsumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; count--; /* consume the item in nextConsumed }
Race Condition • count++ could be implemented asregister1 = count register1 = register1 + 1 count = register1 • count-- could be implemented asregister2 = count register2 = register2 - 1 count = register2 P192
Race Condition • Consider this execution interleaving with “count = 5” initially: S0: producer execute register1 = count {register1 = 5}S1: producer execute register1 = register1 + 1 {register1 = 6} S2: consumer execute register2 = count {register2 = 5} S3: consumer execute register2 = register2 - 1 {register2 = 4} S4: producer execute count = register1 {count = 6 } S5: consumer execute count = register2 {count = 4} Correct result: count=5 P193
Race Condition • A situation like this, where 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, is called a race condition. • we need to ensure that only one process at a time can be manipulating the variable count. To make such a guarantee, we require that the processes be synchronized in some way. 竞争条件(Race Condition) *多个进程并发访问和维护同样的数据, *执行的结果依赖于访问发生时的特定顺序。 P193
Critical-Section Problem • Consider a system consisting of n processes {P0, P 1 , ..., Pn-1). Each process has a segment of code, called a critical section, in which the process may be changing common variables, updating a table, writing a file, and so on. • when one process is executing in its critical section, no other process is to be allowed to execute in its critical section. • Each process must request permission to enter its critical section. The section of code implementing this request is the entry section.
Critical-Section Problem • The critical section may be followed by an exit section. • The remaining code is the remainder section.
临界资源 • 临界资源(Critical resource) • 并发进程可以共享系统中的各种资源,但是系统中的某些资源,例如打印机、磁带机、表格、等,虽然他们可以提供给多个进程使用,但在一段时间内却只允许一个进程访问该资源。当一个进程正在访问该资源时,其他欲访问该资源的进程必须等待,仅当该进程访问完并释放该资源后,才允许另一进程对该资源进行访问。把在一段时间内只允许一个进程访问的资源称为临界资源。即临界资源需要互斥访问。 • 临界区(Critical Section) • 把在每个进程中访问临界资源的那段代码称为临界区。 • 当一个进程正在临界区执行时,其他进程不允许进入他们的临界区执行。
Solution to Critical-Section Problem • A solution to the critical-section problem must satisfy the following four requirements: 1. Mutual Exclusion - If process Pi is executing in its critical section, then no other processes can be executing in their critical sections 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 P194
Solution to Critical-Section Problem • 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 • No Busy waiting-让权等待,不能进入临界区,应释放CPU
Initial Attempts to Solve Problem • Only 2 processes, P0 and P1 • General structure of process Pi(other process Pj) do { entry section critical section exit section reminder section } while (1); • Processes may share some common variables to synchronize their actions.
Algorithm 1 • Shared variables: • int turn;initially turn = 0 • turn= 0 P0 can enter its critical section • Satisfies mutual exclusion, but not progress Process P1 do { while (turn != 1) ; critical section turn = 0; reminder section } while (1); Process P0 do { while (turn != 0) ; critical section turn = 1; reminder section } while (1);
Algorithm 2 • Shared variables • boolean flag[2];initially flag [0] = flag [1] = false. • flag [i] = true Pi ready to enter its critical section • Satisfies mutual exclusion, but not progress requirement. Process P0 do { flag[0] := true; while (flag[1]) ; critical section flag [0] = false; remainder section } while (1); Process P1 do { flag[1] := true; while (flag[0]) ; critical section flag [1] = false; remainder section } while (1);
Algorithm 3--- Peterson’s Solution • Combined shared variables of algorithms 1 and 2. • Meets all three requirements; solves the critical-section problem for two processes. Process P0 do { flag [0]:= true; turn = 1; while (flag [1] and turn = 1); critical section flag [0] = false; remainder section } while (1); Process P1 do { flag [1]:= true; turn = 0; while (flag [0] and turn = 0); critical section flag [1] = false; remainder section } while (1); P196
分析 • 当两个进程几乎同时到达,同时将flag[0] 与flag[1] 同时true;同时将turn置为0与1,但只有一个能够维持; 这样,可以保证两个进程的while循环有一个能够满足,另一个不满足。只允许不满足while循环条件的一个进程进入临界区,而另一个(满足while循环条件)进程等待(满足互斥访问);并且一个进程必然能进入临界区(满足有空让进),且当该进程退出临界区时,将相应的flag[]置为false,使另一个进程的while循环条件不满足,该进程可以使用临界区(满足有限等待)。
Synchronization Hardware • Many systems provide hardware support for critical section code • Uni-processor – could disable interrupts • Currently running code would execute without preemption • Modern machines provide special atomic hardware instructions • Atomic = non-interruptable P197
TestAndSet Instruction • Definition: boolean TestAndSet (boolean *target) { boolean rv = *target; *target = TRUE; return rv: }
Solution using TestAndSet • Shared Boolean variable lock, initialized to false. • Solution: while (true) { while ( TestAndSet (&lock )) ; /* do nothing // critical section lock = FALSE; // remainder section }
Swap Instruction • Definition: void Swap (boolean *a, boolean *b) { boolean temp = *a; *a = *b; *b = temp: } P198
Solution using Swap • Shared Boolean variable lock initialized to FALSE; Each process has a local Boolean variable key. • Solution: while (true) { key = TRUE; while ( key == TRUE) Swap (&lock, &key ); // critical section lock = FALSE; // remainder section }
Semaphore • Semaphore S – integer variable • Two standard operations modify S: wait() and signal() • Originally called P() andV() • Can only be accessed via two indivisible (atomic) operations P200
Semaphore 类型 • Counting semaphores can be used to control access to a given resourceconsisting of a finite number of instances. • The semaphore is initialized to the number of resources available. • Each process that wishes to use a resourceperforms a wait() operation on the semaphore • When a process releases a resource, it performs a signal() operation • When the countfor the semaphore goes to 0, allresources are being used. After that, processes that wish to use a resource willblock until the count becomes greater than 0. P201
Semaphore 类型 • The value of a binary semaphore can range only between 0 and 1. • On some systems, binary semaphores are known as mutex locks, as they are locks that provide mutual exclusion
Semaphore as General Synchronization Tool • Provides mutual exclusion • Semaphore S; // initialized to 1 wait (S); Critical Section signal (S);
Solve Various Synchronization Problems • consider two concurrently running processes: P1 with a statement S1 and P2 with a statement S2. • Suppose we require that S2 be executed only after S1 has completed. • We can implement this scheme readily by letting P1 and P2 share a common semaphore synch, initialized to 0 P1 P2 S1; signal (synch) ; wait (synch) ; S2; P201
Semaphore Implementation • Must guarantee that no two processes can execute wait () and signal () on the same semaphore at the same time • Thus, implementation becomes the critical section problem where the wait and signal code are placed in the critical section. • Note that applications may spend lots of time in critical sections and therefore this is not a good solution. P202
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 list • Two operations: • 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.
分析 • value的初值表示系统中某类资源的数目,因而又称为资源信号量, • 每次的wait操作,意味着进程请求一个单位的资源,描述为value--;当value<0 时,表示资源已经分配完毕,因而进程自我阻塞,放弃处理机,添加到等待进程队列中。此时,value的绝对值表示在该信号量链中已经阻塞的进程的数目。 • 每次signal操作表示执行进程释放一个单位资源,故表示为value++,表示资源数目加1。若加1后仍满足value<=0,表示该信号量链中仍有等该资源的进程被阻塞,故还应该将其中的一个进程唤醒。
实现机制 • The list of waiting processes can be easily implemented by a link field in each process control block (PCB). • The critical aspect of semaphores is that they be executed atomically. We must guarantee that no two processes can execute wait ( ) and signal ( ) operations on the same semaphore at the same time. • in a single-processor environment (that is, where only one CPU exists), we can solve it by simply inhibiting interrupts during the time the wait ( ) and signal () operations are executing. • wait()和signal()必须成对出现,使用资源后必须释放资源。 P203
Deadlock and Starvation • Deadlock – two or more 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 1 P0P1 wait (S); wait (Q); wait (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. P204
Classical Problems of Synchronization • 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. • 表示空闲的缓冲区数目或请求情况 P205
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.Problem – allow multiple readers to read at the same time. Only one single writer can access the shared data at the same time. P206
Readers-Writers Problem • The readers-writers problem has several variations, all involving priorities. • The first readers-writers problem, requires that no reader will be kept waiting unless a writer has already obtained permission to use the shared object. In other words, no reader should wait for other readers to finish simply because a writer is waiting. • The second readers-writers problem, requires that, once a writer is ready, that writer performs its write as soon as possible. In other words, if a writer is waiting to access the object, no new readers may start reading. • A solution to either problem may result in starvation. In the first case, writers may starve; in the second case, readers may starve.
Readers-Writers Problem • first readers-writers problem • Semaphore mutex initialized to 1. • 用于对readerCount的互斥访问 • Semaphore wrt initialized to 1. • 用于读者-写者以及写者-写者之间的互斥 • Integer readcount initialized to 0. • 标识读者数目
Dining-Philosophers Problem • 问题描述 P208
Dining-Philosophers Problem • The dining-philosophers problemis considered a classic synchronization problem neither because of its practical importance nor because computer scientists dislike philosophers but because it is an example of a large class of concurrency-control problems. • It is a simple representation of the need to allocate several resources among several processes in a deadlock-free and starvation-free manner.
Dining-Philosophers Problem (Cont.) • Semaphore chopstick [5] initialized to 1 • The structure of Philosopher i: While (true) { wait ( chopstick[i] ); wait ( chopStick[ (i + 1) % 5] ); // eat signal ( chopstick[i] ); signal (chopstick[ (i + 1) % 5] ); // think }
Dining-Philosophers Problem (Cont.) • it could create a deadlock. Suppose that all five philosophers become hungry simultaneously and each grabs her left chopstick. All the elements of chopstick will now be equal to 0. When each philosopher tries to grab her right chopstick, she will be delayed forever. • 解决的办法 • 至多允许四个哲学家进餐; • 仅当左右筷子均可用时,才允许他拿起筷子进餐; • 规定奇数号哲学家先拿左边的筷子,再去拿右边的筷子。而偶数号哲学家则相反。 P209
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) 信号量机制虽能解决同步问题,但需要程序员显式地编程
Monitors • A high-level abstraction that provides a convenient and effective mechanism for process synchronization • Only one process may be active within the monitor at a time monitor monitor-name { // shared variable declarations procedure P1 (…) { …. } … procedure Pn (…) {……} Initialization code ( ….) { … } …} P209
Monitors • 一个管程定义了一个数据结构和能为并发进程所执行的一组操作,这组操作能同步进程和改变管程中的数据。[面向对象的思想] • 管程相当于围墙,它把共享变量和对它进行操作的若干过程围了起来,所有进程要访问临界资源时,都必须经过管程(相当于通过围墙的门)才能进入,而管程每次只允许一个进程进入管程,从而实现了进程之间的互斥。