Chapter 5 Process Synchronization Operating System Concepts 9

  • Slides: 40
Download presentation
Chapter 5: Process Synchronization Operating System Concepts – 9 th Edition Silberschatz, Galvin and

Chapter 5: Process Synchronization Operating System Concepts – 9 th Edition Silberschatz, Galvin and Gagne © 2013

Chapter 5: Process Synchronization n n Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware

Chapter 5: Process Synchronization n n Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Mutex Locks Semaphores Classic Problems of Synchronization Monitors Synchronization Examples Alternative Approaches Operating System Concepts – 9 th Edition 5. 2 Silberschatz, Galvin and Gagne © 2013

Objectives n To present the concept of process synchronization. n To introduce the critical-section

Objectives n To present the concept of process synchronization. n To introduce the critical-section problem, whose solutions can be used to ensure the consistency of shared data n To present both software and hardware solutions of the critical-section problem n To examine several classical process-synchronization problems n To explore several tools that are used to solve process synchronization problems Operating System Concepts – 9 th Edition 5. 3 Silberschatz, Galvin and Gagne © 2013

Background n Processes can execute concurrently l May be interrupted at any time, partially

Background n Processes can execute concurrently l May be interrupted at any time, partially completing execution n Concurrent access to shared data may result in data inconsistency n Maintaining data consistency requires mechanisms to ensure the orderly execution of cooperating processes n Illustration of the problem: 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 counter that keeps track of the number of full buffers. Initially, counter 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. Operating System Concepts – 9 th Edition 5. 4 Silberschatz, Galvin and Gagne © 2013

Producer Let’s return to our consideration of the bounded buffer. Here, we assume that

Producer Let’s return to our consideration of the bounded buffer. Here, we assume that the code for the producer is as follows: while (true) { /* produce an item in next produced */ while (counter == BUFFER_SIZE) ; /* do nothing */ buffer[in] = next_produced; in = (in + 1) % BUFFER_SIZE; counter++; } Operating System Concepts – 9 th Edition 5. 5 Silberschatz, Galvin and Gagne © 2013

Consumer The code for the consumer is while (true) { while (counter == 0)

Consumer The code for the consumer is while (true) { while (counter == 0) ; /* do nothing */ next_consumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; counter--; /* consume the item in next consumed */ } n Although both the producer and consumer routines are correct separately, they may not function correctly when executed concurrently. n As an illustration, suppose that the value of the variable count is currently 5 and that the producer and consumer processes execute the statements “++count” and “--count” concurrently. n Following the execution of these two statements, the value of the variable count may be 4, 5, or 6! The only correct result, though, is count == 5, which is generated correctly if the producer and consumer execute separately. Operating System Concepts – 9 th Edition 5. 6 Silberschatz, Galvin and Gagne © 2013

Race Condition n We can show that the value of count may be incorrect

Race Condition n We can show that the value of count may be incorrect as follows. Note that the statement “++count” may be implemented in machine language: register 1 = counter register 1 = register 1 + 1 counter = register 1 n counter-- could be implemented as register 2 = counter register 2 = register 2 - 1 counter = register 2 n Consider this execution interleaving with “count = 5” initially: T 0: producer execute register 1 = counter T 1: producer execute register 1 = register 1 + 1 T 2: consumer execute register 2 = counter T 3: consumer execute register 2 = register 2 – 1 T 4: producer execute counter = register 1 T 5: consumer execute counter = register 2 Operating System Concepts – 9 th Edition 5. 7 {register 1 = 5} {register 1 = 6} {register 2 = 5} {register 2 = 4} {counter = 6 } {counter = 4} Silberschatz, Galvin and Gagne © 2013

Race Condition n If we reversed the order of the statements at T 4

Race Condition n If we reversed the order of the statements at T 4 and T 5, we would arrive at the incorrect state “count == 6”. n We would arrive at this incorrect state because we allowed both processes to manipulate the variable count concurrently. n 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. Operating System Concepts – 9 th Edition 5. 8 Silberschatz, Galvin and Gagne © 2013

Critical Section Problem n Consider system of n processes {p 0, p 1, …

Critical Section Problem n Consider system of n processes {p 0, p 1, … pn-1} n Each process has critical section segment of code in which Process may be changing common variables, updating table, writing file, and so on. n The important feature of the system is that, when one process is executing in its critical section, no other process is to be allowed to execute in its critical section. n That is, no two processes are executing in their critical sections at the same time. n Critical section problem is to design a protocol that the processes can use to cooperate. n Each process must request permission to enter its critical section. The section of code implementing this request is the entry section. The critical section may be followed by an exit section. The remaining code is the remainder section Operating System Concepts – 9 th Edition 5. 9 Silberschatz, Galvin and Gagne © 2013

Critical Section n General structure of process Pi Operating System Concepts – 9 th

Critical Section n General structure of process Pi Operating System Concepts – 9 th Edition 5. 10 Silberschatz, Galvin and Gagne © 2013

Solution to Critical-Section Problem A solution to the critical-section problem must satisfy the following

Solution to Critical-Section Problem A solution to the critical-section problem must satisfy the following three 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 some processes wish to enter their critical sections, then only those processes that are not executing in their remainder sections can participate in deciding which will enter its critical section next, and this selection cannot be postponed indefinitely. 3. Bounded Waiting - There exists a bound, or limit, 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. Operating System Concepts – 9 th Edition 5. 11 Silberschatz, Galvin and Gagne © 2013

Critical-Section Handling in OS Two general approaches are used to handle critical sections in

Critical-Section Handling in OS Two general approaches are used to handle critical sections in operating systems: l Preemptive kernels– allows a process to be preempted while it is running in kernel mode. l Non-preemptive kernels– does not allow a process running in kernel mode to be preempted; Operating System Concepts – 9 th Edition 5. 12 Silberschatz, Galvin and Gagne © 2013

Peterson’s Solution n Peterson’s solution is restricted to two processes that alternate execution between

Peterson’s Solution n Peterson’s solution is restricted to two processes that alternate execution between their critical sections and remainder sections. n The processes are numbered P 0 and P 1. n For convenience, when presenting Pi , we use Pj to denote the other process; . n Peterson’s solution requires the two processes to share two data items: int turn; l Boolean flag[2] l n The variable turn indicates whose turn it is to enter its critical section. That is, if turn == i, then process Pi is allowed to execute in its critical section. n The flag array is used to indicate if a process is ready to enter its critical section. For example, if flag[i] is true, this value indicates that Pi is ready to enter its critical section. Operating System Concepts – 9 th Edition 5. 13 Silberschatz, Galvin and Gagne © 2013

Algorithm for Process Pi do { flag[i] = true; turn = j; while (flag[j]

Algorithm for Process Pi do { flag[i] = true; turn = j; while (flag[j] && turn = = j); critical section flag[i] = false; remainder section } while (true); n To enter the critical section, process Pi first sets flag[i] to be true and then sets turn to the value j, n The eventual value of turn determines which of the two processes is allowed to enter its critical section first. Operating System Concepts – 9 th Edition 5. 14 Silberschatz, Galvin and Gagne © 2013

Peterson’s Solution (Cont. ) n Provable that the three CS requirement are met: 1.

Peterson’s Solution (Cont. ) n Provable that the three CS requirement are met: 1. Mutual exclusion is preserved 4 P 0 and P 1 could not have successfully executed their critical section at about the same time, since the value of turn can be either 0 or 1 but cannot be both. 2. Progress requirement is satisfied 4 A process Pi has value of flag[i] = false just before entering its reminder section so it cant executing its critical section until its finish executing there reminder section and then it will be decide if its can enter its critical section or not. 3. Bounded-waiting requirement is met 4 since Pi does not change the value of the variable turn while executing the while statement, Pi will enter the critical section (progress) after at most one entry by Pj (bounded waiting). Operating System Concepts – 9 th Edition 5. 15 Silberschatz, Galvin and Gagne © 2013

Synchronization Hardware n Many systems provide hardware support for implementing the critical section code.

Synchronization Hardware n Many systems provide hardware support for implementing the critical section code. n All solutions below based on idea of locking l Protecting critical regions via locks n Uniprocessors – could disable interrupts l Currently running code would execute without preemption l Generally too inefficient on multiprocessor systems 4 Operating systems using this not broadly scalable n Modern machines provide special atomic hardware instructions 4 Atomic = non-interruptible Either test memory word and set value l Or swap contents of two memory words l Operating System Concepts – 9 th Edition 5. 16 Silberschatz, Galvin and Gagne © 2013

Solution to Critical-section Problem Using Locks do { acquire lock critical section release lock

Solution to Critical-section Problem Using Locks do { acquire lock critical section release lock remainder section } while (TRUE); Operating System Concepts – 9 th Edition 5. 17 Silberschatz, Galvin and Gagne © 2013

Mutex Locks n Previous solutions are complicated and generally inaccessible to application programmers n

Mutex Locks n Previous solutions are complicated and generally inaccessible to application programmers n OS designers build software tools to solve critical section problem n Simplest is mutex lock n Protect a critical section by first acquire() a lock then release() the lock l Boolean variable indicating if lock is available or not n Calls to acquire() and release() must be atomic l Usually implemented via hardware atomic instructions Atomic = non-interruptible n But this solution requires busy waiting n This lock therefore called a spinlock l Operating System Concepts – 9 th Edition 5. 18 Silberschatz, Galvin and Gagne © 2013

acquire() and release() n acquire() { while (!available) ; /* busy wait */ available

acquire() and release() n acquire() { while (!available) ; /* busy wait */ available = false; } n release() { available = true; } n do { acquire lock critical section release lock remainder section } while (true); Operating System Concepts – 9 th Edition 5. 19 Silberschatz, Galvin and Gagne © 2013

Semaphore n Synchronization tool that provides more sophisticated ways (than Mutex locks) for process

Semaphore n Synchronization tool that provides more sophisticated ways (than Mutex locks) for process to synchronize their activities. Semaphore S – integer variable n Can only be accessed via two indivisible (atomic) operations n wait() and signal() 4 Originally called P() and V() n Definition of the wait() operation wait(S) { l while (S <= 0) ; // busy wait S--; } n Definition of the signal() operation signal(S) { S++; } Operating System Concepts – 9 th Edition 5. 20 Silberschatz, Galvin and Gagne © 2013

Semaphore Usage n Counting semaphore – integer value can range over an unrestricted domain

Semaphore Usage n Counting semaphore – integer value can range over an unrestricted domain l n Binary semaphore – integer value can range only between 0 and 1 l n Counting semaphores can be used to control access to a given resource consisting of a finite number of instances. The semaphore is initialized to the number of resources available. Each process that wishes to use a resource performs a wait() operation on the semaphore (thereby decrementing the count). When a process releases a resource, it performs a signal() operation (incrementing the count). When the count for the semaphore goes to 0, all resources are being used. After that, processes that wish to use a resource will block until the count becomes greater than 0. Same as a mutex lock Can solve various synchronization problems l Consider P 1 and P 2 that require S 1 to happen before S 2 4 Create a semaphore “synch” initialized to 0 P 1: S 1 ; signal(synch); P 2: wait(synch); S 2 ; Operating System Concepts – 9 th Edition 5. 21 Silberschatz, Galvin and Gagne © 2013

Deadlock and Starvation n Deadlock – two or more processes are waiting indefinitely for

Deadlock and Starvation n Deadlock – two or more processes are waiting indefinitely for an event that can be caused by only one of the waiting processes n Let S and Q be two semaphores initialized to 1 P 0 P 1 wait(S); wait(Q); . . . signal(S); signal(Q); wait(S); . . . signal(Q); signal(S); l Suppose that P 0 executes wait(S) and then P 1 executes wait(Q). l When P 0 executes wait(Q), it must wait until P 1 executes signal(Q). l Similarly, when P 1 executes wait(S), it must wait until P 0 executes signal(S). l Since these signal() operations cannot be executed, P 0 and P 1 are deadlocked. n Starvation – indefinite blocking l A process may never be removed from the semaphore queue in which it is suspended Operating System Concepts – 9 th Edition 5. 22 Silberschatz, Galvin and Gagne © 2013

Priority Inversion n Priority Inversion – Scheduling problem when lower-priority process holds a lock

Priority Inversion n Priority Inversion – Scheduling problem when lower-priority process holds a lock needed by higher-priority process n Solved via priority-inheritance protocol, l According to this protocol, all processes that are accessing resources needed by a higher-priority process inherit the higher priority until they are finished with the resources in question. l When they are finished, their priorities revert to their original values Operating System Concepts – 9 th Edition 5. 23 Silberschatz, Galvin and Gagne © 2013

Classical Problems of Synchronization n Classical problems used to test newly-proposed synchronization schemes l

Classical Problems of Synchronization n Classical problems used to test newly-proposed synchronization schemes l Bounded-Buffer Problem l Readers and Writers Problem l Dining-Philosophers Problem Operating System Concepts – 9 th Edition 5. 24 Silberschatz, Galvin and Gagne © 2013

Bounded-Buffer Problem n In our problem, the producer and consumer processes share the following

Bounded-Buffer Problem n In our problem, the producer and consumer processes share the following data structures: l n buffers, each can hold one item l Semaphore mutex initialized to the value 1 l Semaphore full initialized to the value 0 l Semaphore empty initialized to the value n l The empty and full semaphores count the number of empty and full buffers. l The mutex semaphore provides mutual exclusion for accesses to the buffers. Operating System Concepts – 9 th Edition 5. 25 Silberschatz, Galvin and Gagne © 2013

Bounded Buffer Problem (Cont. ) n The structure of the producer process do {.

Bounded Buffer Problem (Cont. ) n The structure of the producer process do {. . . /* produce an item in next_produced */. . . wait(empty); wait(mutex); . . . /* add next produced to the buffer */. . . signal(mutex); signal(full); } while (true); Operating System Concepts – 9 th Edition 5. 26 Silberschatz, Galvin and Gagne © 2013

Bounded Buffer Problem (Cont. ) n The structure of the consumer process Do {

Bounded Buffer Problem (Cont. ) n The structure of the consumer process Do { wait(full); wait(mutex); . . . /* remove an item from buffer to next_consumed */. . . signal(mutex); signal(empty); . . . /* consume the item in next consumed */. . . } while (true); Operating System Concepts – 9 th Edition 5. 27 Silberschatz, Galvin and Gagne © 2013

Readers-Writers Problem n A data set is shared among a number of concurrent processes

Readers-Writers Problem n A data set is shared among a number of concurrent processes l Readers – only read the data set; they do not perform any updates l Writers – can both read and write n Problem – allow multiple readers to read at the same time l Only one single writer can access the shared data at the same time n Several variations of how readers and writers are considered – all involve some form of priorities n In the solution to the first readers–writers problem, the reader processes share the following data structures: l semaphore rw mutex = 1; l semaphore mutex = 1; l int read_count = 0; n The mutex semaphore is used to ensure mutual exclusion when the variable read_count is updated. n The read count variable keeps track of how many processes are currently reading the object. Operating System Concepts – 9 th Edition 5. 28 Silberschatz, Galvin and Gagne © 2013

Readers-Writers Problem (Cont. ) n The semaphore rw_mutex functions as a mutual exclusion semaphore

Readers-Writers Problem (Cont. ) n The semaphore rw_mutex functions as a mutual exclusion semaphore for the writers. It is also used by the first or last reader that enters or exits the critical section. It is not used by readers who enter or exit while other readers are in their critical sections. n The structure of a writer process do { wait(rw_mutex); . . . /* writing is performed */. . . signal(rw_mutex); } while (true); Operating System Concepts – 9 th Edition 5. 29 Silberschatz, Galvin and Gagne © 2013

Readers-Writers Problem (Cont. ) n The structure of a reader process do { wait(mutex);

Readers-Writers Problem (Cont. ) n The structure of a reader process do { wait(mutex); read_count++; if (read_count == 1) wait(rw_mutex); signal(mutex); . . . /* reading is performed */. . . wait(mutex); read count--; if (read_count == 0) signal(rw_mutex); signal(mutex); } while (true); Operating System Concepts – 9 th Edition 5. 30 Silberschatz, Galvin and Gagne © 2013

Dining-Philosophers Problem n Philosophers spend their lives alternating thinking and eating n Don’t interact

Dining-Philosophers Problem n Philosophers spend their lives alternating thinking and eating n Don’t interact with their neighbors, occasionally try to pick up 2 chopsticks (one at a time) to eat from bowl l n Need both to eat, then release both when done In the case of 5 philosophers l Shared data 4 Bowl of rice (data set) 4 Semaphore chopstick [5] initialized to 1 Operating System Concepts – 9 th Edition 5. 31 Silberschatz, Galvin and Gagne © 2013

Dining-Philosophers Problem Algorithm n The structure of Philosopher i: do { wait (chopstick[i] );

Dining-Philosophers Problem Algorithm n The structure of Philosopher i: do { wait (chopstick[i] ); wait (chop. Stick[ (i + 1) % 5] ); // eat signal (chopstick[i] ); signal (chopstick[ (i + 1) % 5] ); // think } while (TRUE); n What is the problem with this algorithm? Operating System Concepts – 9 th Edition 5. 32 Silberschatz, Galvin and Gagne © 2013

Problems with Semaphores 1. Incorrect use of semaphore operations. l Suppose that a process

Problems with Semaphores 1. Incorrect use of semaphore operations. l Suppose that a process interchanges the order in which the wait() and signal() operations on the semaphore mutex are executed, resulting in the following execution: 4 l Suppose that a process replaces signal(mutex) with wait(mutex). That is, it executes: 4 l In this situation, several processes maybe executing in their critical sections simultaneously, In this case, a deadlock will occur. Suppose that a process omits the wait(mutex), or the signal(mutex), or both. In this case, either mutual exclusion is violated or a deadlock will occur. 2. Deadlock and starvation are possible. Operating System Concepts – 9 th Edition 5. 33 Silberschatz, Galvin and Gagne © 2013

Monitors A high-level abstraction that provides a convenient and effective mechanism for process synchronization

Monitors A high-level abstraction that provides a convenient and effective mechanism for process synchronization n Abstract data type, internal variables only accessible by code within the procedure n Only one process may be active within the monitor at a time n But not powerful enough to model some synchronization schemes n monitor-name { // shared variable declarations procedure P 1 (…) { …. } procedure Pn (…) {……} Initialization code (…) { … } } } n For this purpose, we need to define additional synchronization mechanisms. These mechanisms are provided by the condition Operating System Concepts – 9 th Edition 5. 34 Silberschatz, Galvin and Gagne © 2013

Schematic view of a Monitor Operating System Concepts – 9 th Edition 5. 35

Schematic view of a Monitor Operating System Concepts – 9 th Edition 5. 35 Silberschatz, Galvin and Gagne © 2013

Condition Variables n condition x, y; n Two operations are allowed on a condition

Condition Variables n condition x, y; n Two operations are allowed on a condition variable: l x. wait() – a process that invokes the operation is suspended until x. signal()– resumes one of processes (if any) that another process invokes x. wait() 4 The x. signal() operation resumes exactly one suspended process. If no process is suspended, then the signal() operation has no effect; Operating System Concepts – 9 th Edition 5. 36 Silberschatz, Galvin and Gagne © 2013

Monitor with Condition Variables Operating System Concepts – 9 th Edition 5. 37 Silberschatz,

Monitor with Condition Variables Operating System Concepts – 9 th Edition 5. 37 Silberschatz, Galvin and Gagne © 2013

Condition Variables Choices n If process P invokes x. signal(), and process Q is

Condition Variables Choices n If process P invokes x. signal(), and process Q is suspended in x. wait(), what should happen next? l Both Q and P cannot execute in paralel. If Q is resumed, then P must wait n Options include l Signal and wait – P waits until Q either leaves the monitor or it waits for another condition l Signal and continue – Q waits until P either leaves the monitor or it waits for another condition l Implemented in other languages including Mesa, C#, Java Operating System Concepts – 9 th Edition 5. 38 Silberschatz, Galvin and Gagne © 2013

Resuming Processes within a Monitor n If several processes queued on condition x, and

Resuming Processes within a Monitor n If several processes queued on condition x, and x. signal() executed, which should be resumed? n FCFS frequently not adequate n conditional-wait construct of the form x. wait(c) l Where c is priority number l When x. signal() is executed; Process with lowest number (highest priority) is scheduled next Operating System Concepts – 9 th Edition 5. 39 Silberschatz, Galvin and Gagne © 2013

End of Chapter 5 Operating System Concepts – 9 th Edition Silberschatz, Galvin and

End of Chapter 5 Operating System Concepts – 9 th Edition Silberschatz, Galvin and Gagne © 2013