Chapter 6: Process Synchronization. Module 6: Process Synchronization



Similar documents
OPERATING SYSTEMS PROCESS SYNCHRONIZATION

Lecture 6: Semaphores and Monitors

Chapter 1 FUNDAMENTALS OF OPERATING SYSTEM

OS OBJECTIVE QUESTIONS

Comp 5311 Database Management Systems. 16. Review 2 (Physical Level)

218 Chapter 5 CPU Scheduling

Chapter 14: Recovery System

Chapter 15: Recovery System

Concepts of Concurrent Computation

A Survey of Parallel Processing in Linux

Chapter 10. Backup and Recovery

Textbook and References

Resource Allocation and Deadlock Resource Allocation and Handling

OPERATING SYSTEMS Internais and Design Principles

Chapter 7: Deadlocks!

Outline of this lecture G52CON: Concepts of Concurrency

Database Concurrency Control and Recovery. Simple database model

Monitors, Java, Threads and Processes

SYSTEM ecos Embedded Configurable Operating System

Last Class: Semaphores

Computer Science 4302 Operating Systems. Student Learning Outcomes

Chapter 6, The Operating System Machine Level

Chapter 16: Recovery System

Review: The ACID properties

Tasks Schedule Analysis in RTAI/Linux-GPL

SSC - Concurrency and Multi-threading Java multithreading programming - Synchronisation (I)

Linux Process Scheduling Policy

Multiprocessor Scheduling and Scheduling in Linux Kernel 2.6

Operating Systems 4 th Class

Operating Systems, 6 th ed. Test Bank Chapter 7

Recovery and the ACID properties CMPUT 391: Implementing Durability Recovery Manager Atomicity Durability

Mutual Exclusion using Monitors

CS414 SP 2007 Assignment 1

Concurrency Control. Module 6, Lectures 1 and 2

Chapter 1 8 Essay Question Review

COS 318: Operating Systems

Deciding which process to run. (Deciding which thread to run) Deciding how long the chosen process can run

Course Content. Transactions and Concurrency Control. Objectives of Lecture 4 Transactions and Concurrency Control

Linux A multi-purpose executive support for civil avionics applications?

! Volatile storage: ! Nonvolatile storage:

Shared Address Space Computing: Programming

Operating System: Scheduling

Lesson 12: Recovery System DBMS Architectures

Operating Systems Concepts: Chapter 7: Scheduling Strategies

Synchronization. Todd C. Mowry CS 740 November 24, Topics. Locks Barriers

Linux Scheduler. Linux Scheduler

Lesson Objectives. To provide a grand tour of the major operating systems components To provide coverage of basic computer system organization

(Pessimistic) Timestamp Ordering. Rules for read and write Operations. Pessimistic Timestamp Ordering. Write Operations and Timestamps

Computer-System Architecture

Semaphores and Monitors: High-level Synchronization Constructs

Chapter 11 I/O Management and Disk Scheduling

CS Fall 2008 Homework 2 Solution Due September 23, 11:59PM

UVA. Failure and Recovery. Failure and inconsistency. - transaction failures - system failures - media failures. Principle of recovery

Replication on Virtual Machines

Real Time Programming: Concepts

Chapter 10: Distributed DBMS Reliability

CS0206 OPERATING SYSTEMS Prerequisite CS0201, CS0203

Linux scheduler history. We will be talking about the O(1) scheduler

Transaction Processing Monitors

Process Scheduling CS 241. February 24, Copyright University of Illinois CS 241 Staff

! Past few lectures: Ø Locks: provide mutual exclusion Ø Condition variables: provide conditional synchronization

An Implementation Of Multiprocessor Linux

Chapter 2: OS Overview

How To Understand The History Of An Operating System

Chapter 5 Process Scheduling

Processes and Non-Preemptive Scheduling. Otto J. Anshus

How To Write A Transaction System

6 Synchronization with Semaphores

Concurrency Control. Chapter 17. Comp 521 Files and Databases Fall

Chapter 1 13 Essay Question Review

COMMMUNICATING COOPERATING PROCESSES

Transactions and the Internet

Chapter 5: CPU Scheduling. Operating System Concepts 8 th Edition

Recovery System C H A P T E R16. Practice Exercises

Information Systems. Computer Science Department ETH Zurich Spring 2012

Lecture Notes on Linear Search

Gildart Haase School of Computer Sciences and Engineering

CPU Scheduling Outline

Operating System Manual. Realtime Communication System for netx. Kernel API Function Reference.

Operating Systems OBJECTIVES 7.1 DEFINITION. Chapter 7. Note:

Database Tuning and Physical Design: Execution of Transactions

Outline. Failure Types

Introduction to Database Management Systems

How To Recover From Failure In A Relational Database System

Transaction Management Overview

Transactions and Recovery. Database Systems Lecture 15 Natasha Alechina

Operating Systems for Parallel Processing Assistent Lecturer Alecu Felician Economic Informatics Department Academy of Economic Studies Bucharest

Objectives. Chapter 5: Process Scheduling. Chapter 5: Process Scheduling. 5.1 Basic Concepts. To introduce CPU scheduling

COS 318: Operating Systems. Semaphores, Monitors and Condition Variables

Concurrent Programming

Overview Motivating Examples Interleaving Model Semantics of Correctness Testing, Debugging, and Verification

Control 2004, University of Bath, UK, September 2004

Linux Driver Devices. Why, When, Which, How?

Embedded Programming in C/C++: Lesson-1: Programming Elements and Programming in C

Operating System Tutorial

Project No. 2: Process Scheduling in Linux Submission due: April 28, 2014, 11:59pm

Concurrency Control: Locking, Optimistic, Degrees of Consistency

Transcription:

Chapter 6: Process Synchronization Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization Examples Atomic Transactions 6.2 Silberschatz, Galvin and Gagne 2005 1

Background: Producer-Consumer Problem Paradigm for cooperating processes, producer process produces information that is consumed by a consumer process unbounded-buffer places no practical limit on the size of the buffer Consumer may have to wait Producer can always produce new item bounded-buffer assumes that there is a fixed buffer size 6.3 Silberschatz, Galvin and Gagne 2005 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. 6.4 Silberschatz, Galvin and Gagne 2005 2

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++; 6.5 Silberschatz, Galvin and Gagne 2005 Consumer while (true) { while (count == 0) ; // do nothing nextconsumed = buffer[out]; out = (out + 1) % BUFFER_SIZE; count--; /* consume the item in nextconsumed 6.6 Silberschatz, Galvin and Gagne 2005 3

Processus concurrents Les processus sont exécutés en parallèle Les commutations sont indépendantes du programme des processus On ne peut pas (et doit pas) faire d hypothèse sur l ordre relatif des exécutions Seuls comptent L ordre d exécution interne d un processus Les relations logiques entre les processus (synchronisation) 6.7 Silberschatz, Galvin and Gagne 2005 Race Condition count++ 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 {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 6.8 Silberschatz, Galvin and Gagne 2005 4

Incorrect state Counter == 4 whereas 5 buffers are full Reversing statement S4 and S5 also gives an incorrect state Counter == 6 Both processes are allowed to manipulate the variable counter concurrently If the outcome of the execution depends on the particular order in which the access take place by several processes is called a race condition 6.9 Silberschatz, Galvin and Gagne 2005 Sections critiques et actions atomiques Comment protéger les accès aux variables partagées Assurer qu un ensemble d opérations sont exécuté de manière indivisible (atomique) Si A1 et A2 sont atomiques Les seules exécutions possibles sont A1; A2 ou A2; A1 Section critique Un ensemble d opérations qui ne doit pas être exécuté de façon concurrente Exclusion mutuelle Permettre un accès exclusif à un ensemble d instructions 6.10 Silberschatz, Galvin and Gagne 2005 5

Section critique Les opérations «entrée en section critique» et «sortie de section critique» doivent garantir l exclusion mutuelle 6.11 Silberschatz, Galvin and Gagne 2005 Réalisation d une d section critique Attente active Le processus qui attend la section critique boucle sur le test d entrée Méthode très inefficace Fonctionne s il n y a qu un processeurs Utiliser parfois en mode noyau pour de très courtes sections Primitives spéciales Elles doivent être atomiques 6.12 Silberschatz, Galvin and Gagne 2005 6

Réalisation d une d section critique Try again 6.13 Silberschatz, Galvin and Gagne 2005 Solution to Critical-Section Problem 1. Mutual Exclusion - If process P i 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 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 6.14 Silberschatz, Galvin and Gagne 2005 7

Preemptive / non preemptive Non preemptive kernel Does not allow a process running in kernel mode to be preempted A kernel mode process will run until it exits kernel mode Blocks Yield the CPU free from RACE condition on kernel data structure Preemptive kernel Allow a process to be preempted while it is running in kernel mode should be carefully designed Especially difficult to design on SMP architecture 2 kernel mode process could run simultaneously 6.15 Silberschatz, Galvin and Gagne 2005 Why anyone would favor preemptive over non preemptive? Preemptive more suitable for real time real time process is able to preempt a process currently running in the kernel Preemptive kernel may be more responsive Less risk that a kernel-mode process will run for an arbitrarily long period before relinquishing the CPU to waiting processes XP/2000 are non preemptive > Linux 2.6 preemptive as Solaris and IRIX 6.16 Silberschatz, Galvin and Gagne 2005 8

Peterson s s Solution Software based solution Two process solution P 0 and P 1 Assume that the LOAD and STORE instructions are atomic; that is, cannot be interrupted. The two processes share two variables: int turn; Boolean flag[2] 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. flag[i] = true implies that process P i is ready! 6.17 Silberschatz, Galvin and Gagne 2005 Algorithm for Process P i while (true) { flag[i] = TRUE; turn = j; while ( flag[j] && turn == j); // CRITICAL SECTION flag[i] = FALSE; Process P_i first set flag to TRUE And set turn to j asserting that if the other process whishes to enter the Critical Section, it can do so. If both processes try to enter at the same time, turn will be set to both i and j at roughly the same time // REMAINDER SECTION Only one of these assignment will last 6.18 Silberschatz, Galvin and Gagne 2005 9

Proof Mutual exclusion is preserved Progress requirement is satisfied Bounded waiting time is met 6.19 Silberschatz, Galvin and Gagne 2005 Proof Mutual exclusion is preserved P_i enters its critical section only if flag[j]==false OR turn==i If both processes are in critical then Flag[0]==flag[1]==TRUE P_0 and P1 can not have successfully executed their while at the same time Since turn is either 0 or 1 but not both P_i did and P_j not At that time flag[j]==true AND turn==j This condition will persist as long as P_j is in its critical section MUTUAL exclusion is preserved 6.20 Silberschatz, Galvin and Gagne 2005 10

Proof Progress requirement is satisfied && Bounded waiting time is met P_i can be prevented from entering only if Flag[j]==true and turn==j (while loop condition / only loop) If P_j is not ready to enter Flag[j]==false and P_i can enter If P_j has set flag[j] to TRUE and it is in the loop then Either turn == I or turn == j If turn == i the P_i will enter If turn == j then P_j will enter Once P_j exists It will set reset flag[j] to true AND set turn to I Since P_i does not change the value of turn during the loop P_i will enter (progress) after at most one entry by P_j (bounded waiting) 6.21 Silberschatz, Galvin and Gagne 2005 Synchronization Hardware We need a lock Many systems provide hardware support for critical section code Uniprocessors could disable interrupts Currently running code would execute without preemption Generally too inefficient on multiprocessor systems Operating systems using this not broadly scalable Disabling interrupts is time consuming in MultiProc Bad effect on a system clock updated by interrupts Modern machines provide special atomic hardware instructions Atomic = non-interruptable Either test memory word and set value Or swap contents of two memory words 6.22 Silberschatz, Galvin and Gagne 2005 11

TestAndSet Instruction Definition: boolean TestAndSet (boolean *target) { boolean rv = *target; *target = TRUE; return rv: 6.23 Silberschatz, Galvin and Gagne 2005 Solution using TestAndSet Shared boolean variable lock., initialized to false. while (true) { while ( TestAndSet (&lock )) ; /* do nothing // critical section lock = FALSE; // remainder section 6.24 Silberschatz, Galvin and Gagne 2005 12

Swap Instruction Definition: void Swap (boolean *a, boolean *b) { boolean temp = *a; *a = *b; *b = temp: 6.25 Silberschatz, Galvin and Gagne 2005 Solution using Swap Shared Boolean variable lock initialized to FALSE; Each process has a local Boolean variable key. while (true) { key = TRUE; while ( key == TRUE) Swap (&lock, &key ); // critical section lock = FALSE; // remainder section 6.26 Silberschatz, Galvin and Gagne 2005 13

Comments Algorithms satisfy the mutual-exclusion But do not satisfy the bounded-waiting time 6.27 Silberschatz, Galvin and Gagne 2005 Bounded waiting mutual exclusion with TestAndSet Shared boolean variable key and boolean array waiting 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 (TRUE) 6.28 Silberschatz, Galvin and Gagne 2005 14

Semaphore Synchronization tool that does not require busy waiting Semaphore S integer variable Two standard operations modify S: wait() and signal() Originally called P() and V() (Puis-je? / Vas-y!) Less complicated Can only be accessed via two indivisible (atomic) operations wait (S) { while S <= 0 S--; signal (S) { S++; ; // no-op When one process modifies the semaphore, no other process can simultaneously modify the same semaphore value 6.29 Silberschatz, Galvin and Gagne 2005 Semaphore as General Synchronization Tool 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 lock that provides mutual exclusion Can use binary semaphore to deal with critical section Provides mutual exclusion Semaphore S; // initialized to 1 wait (S); signal (S); Critical Section 6.30 Silberschatz, Galvin and Gagne 2005 15

Semaphore as General Synchronization Tool Counting semaphore used to control access to a given resource consisting of a finite number of instance Semaphore is initialized to the number of resource To use a resource, P should perform a wait() To release a resource perform a signal() Semaphore == 0 all resources are used Synchronization P_1 with statement S_1 and P_2 with statement S_2 S_2 be executed only after S_1 as completed Semaphore synch initialized to 0 S_1; Signal(synch) Wait(synch) S_2 6.31 Silberschatz, Galvin and Gagne 2005 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. Could now have busy waiting in critical section implementation But implementation code is short Little busy waiting if critical section rarely occupied Busy waiting wastes CPU cycles Spinlock semaphore == the process spins while waiting for the lock Spinlock advantage == no context switch Useful when the lock are expected to be held for short time Note that applications may spend lots of time in critical sections and therefore this is not a good solution. 6.32 Silberschatz, Galvin and Gagne 2005 16

Semaphore Implementation with no Busy waiting To overcome the need of spinlock modify the wait and signal semaphore operations With each semaphore there is an associated waiting queue. Each entry in a waiting queue has two data items: Typedef struct { value (of type integer) int value; pointer to next record in the list struct process *list; Two operations: semaphore 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. 6.33 Silberschatz, Galvin and Gagne 2005 Semaphore Implementation with no Busy waiting (Cont.) Implementation of wait: wait (semaphore *S){ S->value--; if (S->value < 0) { add this process to waiting queue S->list block(); Implementation of signal: Signal (semaphore *S){ S->value++; if (S->value <= 0) { remove a process P from the waiting queue S->list wakeup(p); 6.34 Silberschatz, Galvin and Gagne 2005 17

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 P 0 P 1 wait (S); wait (Q); wait (Q);...... signal (S); signal (Q); wait (S); signal (Q); signal (S); Starvation indefinite blocking. A process may never be removed from the semaphore queue in which it is suspended. 6.35 Silberschatz, Galvin and Gagne 2005 Classical Problems of Synchronization Bounded-Buffer Problem Readers and Writers Problem Dining-Philosophers Problem 6.36 Silberschatz, Galvin and Gagne 2005 18

Producteurs / consommateurs Tampon de messages géré circulairement Producteur Consommateur 6.37 Silberschatz, Galvin and Gagne 2005 Problématique Plusieurs producteurs / plusieurs consommateurs Les producteurs remplissent un buffer Consommateurs le vident Problème Une donnée doit être lue une seule fois Une donnée ne doit pas être écrasée avant d avoir été lue Une case non remplie ne peux être lue 6.38 Silberschatz, Galvin and Gagne 2005 19

Bounded-Buffer 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. 6.39 Silberschatz, Galvin and Gagne 2005 Bounded Buffer Problem (Cont.) The structure of the producer process while (true) { // produce an item wait (empty); wait (mutex); // add the item to the buffer signal (mutex); signal (full); 6.40 Silberschatz, Galvin and Gagne 2005 20

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 6.41 Silberschatz, Galvin and Gagne 2005 Bounded Buffer Problem (Cont.) Symmetry between the producer and consumer Producer produces full buffer for the consumer Consumer produces empty buffer fir the producer 6.42 Silberschatz, Galvin and Gagne 2005 21

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. Shared Data Data set Semaphore mutex initialized to 1. Semaphore wrt initialized to 1. Integer readcount initialized to 0. 6.43 Silberschatz, Galvin and Gagne 2005 Readers-Writers Problem (Cont.) The structure of a writer process while (true) { wait (wrt) ; // writing is performed signal (wrt) ; 6.44 Silberschatz, Galvin and Gagne 2005 22

Readers-Writers Problem (Cont.) The structure of a reader process while (true) { wait (mutex) ; readcount ++ ; if (readcount == 1) wait (wrt) ; signal (mutex) // reading is performed wait (mutex) ; readcount - - ; if (readcount == 0) signal (wrt) ; signal (mutex) ; 6.45 Silberschatz, Galvin and Gagne 2005 Readers-Writers Problem (Cont.) If a writer is in the Critical section and N reader are waiting One reader is queued on WRT N - 1 readers are queued on MUTEX If a writer executes signal(wrt), we may resume the execution of either the waiting readers Or a single waiting writers 6.46 Silberschatz, Galvin and Gagne 2005 23

Lecteur Redacteur Scénario Le rédacteur doit attendre que tous les lecteurs aient fini Mais comme le nombre de lecteurs n est pas bornés Un algorithme doit assurer une certaine équité Eviter les cas de famine 6.47 Silberschatz, Galvin and Gagne 2005 Coalition Ensemble de n processus monopolisant les ressources au détriment de p autres processus R1 Prendre R1 Prendre R2 Traitement P1 Famine R2 Prendre R1 Prendre R2 Traitement P2 6.48 Silberschatz, Galvin and Gagne 2005 24

Une solution plus juste // Lecteur DébutLecture { P(LecEcr); P(MutexLecteur); nblect := nblect + 1; If (nblect = 1) then P(Ecriture); V(MutexLecteur); V(LecEcr); FinLecture { P(MutexLecteur); nblect := nblect - 1; if (nblect = 0) then V(Ecriture); V(MutexLecteur); Init(MutexLecture, 1) Init(LectEcr, 1) Init(Ecriture, 1) nblect = 0 // Redacteurs DébutEcriture { P(LecEcr); P(Ecriture); FinEcriture { V(Ecriture); V(LectEcr); 6.49 Silberschatz, Galvin and Gagne 2005 Lecteur Lecteur Lecteur Redacteur Un résultat r plus juste 6.50 Silberschatz, Galvin and Gagne 2005 25

Dîner des philosophes Problème Quelques philosophes se retrouvent pour manger Ils sont installés autour d une table ronde Un philosophe a besoin de deux baquettes pour manger L activité d un philosophe consiste en : Penser Manger 6.51 Silberschatz, Galvin and Gagne 2005 Dining-Philosophers Problem Shared data Bowl of rice (data set) Semaphore chopstick [5] initialized to 1 6.52 Silberschatz, Galvin and Gagne 2005 26

Dining-Philosophers Problem (Cont.) 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 6.53 Silberschatz, Galvin and Gagne 2005 Problème Tous les philosophes peuvent détenir une baquette Pas d autre baquette disponible Aucun philosophe ne libérera sa baquette tant qu il n aura pas mangé Tous les philosophes sont bloqués 6.54 Silberschatz, Galvin and Gagne 2005 27

Solutions At most 4 philosophers to be sitting simultaneously at the table Allow a philosopher to the chopsticks only if both chopsticks are available (in a critical section) Use asymmetric solution Odd philosopher picks up first the left chopstick and then the right one. Any satisfactory solution MUST guard against the possibility that one philosopher will stave to death Deadlock free does not imply no starvation 6.55 Silberschatz, Galvin and Gagne 2005 Problems with Semaphores Correct use of semaphore operations: signal (mutex). wait (mutex) wait (mutex) wait (mutex) Omitting of wait (mutex) or signal (mutex) (or both) 6.56 Silberschatz, Galvin and Gagne 2005 28

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 (.) { 6.57 Silberschatz, Galvin and Gagne 2005 Schematic view of a Monitor 6.58 Silberschatz, Galvin and Gagne 2005 29

Condition Variables 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 () 6.59 Silberschatz, Galvin and Gagne 2005 Monitor with Condition Variables 6.60 Silberschatz, Galvin and Gagne 2005 30

Solution to Dining Philosophers monitor DP { enum { THINKING; HUNGRY, EATING) state [5] ; condition self [5]; void pickup (int i) { state[i] = HUNGRY; test(i); if (state[i]!= EATING) self [i].wait; void putdown (int i) { state[i] = THINKING; // test left and right neighbors test((i + 4) % 5); test((i + 1) % 5); 6.61 Silberschatz, Galvin and Gagne 2005 Solution to Dining Philosophers (cont) void test (int i) { if ( (state[(i + 4) % 5]!= EATING) && (state[i] == HUNGRY) && (state[(i + 1) % 5]!= EATING) ) { state[i] = EATING ; self[i].signal () ; initialization_code() { for (int i = 0; i < 5; i++) state[i] = THINKING; 6.62 Silberschatz, Galvin and Gagne 2005 31

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) 6.63 Silberschatz, Galvin and Gagne 2005 Monitor Implementation Using Semaphores Variables semaphore mutex; // (initially = 1) semaphore next; // (initially = 0) int next-count = 0; Each procedure F will be replaced by wait(mutex); body of F; if (next-count > 0) signal(next) else signal(mutex); Mutual exclusion within a monitor is ensured. 6.64 Silberschatz, Galvin and Gagne 2005 32

Monitor Implementation For each condition variable x, we have: semaphore x-sem; // (initially = 0) int x-count = 0; The operation x.wait can be implemented as: x-count++; if (next-count > 0) signal(next); else signal(mutex); wait(x-sem); x-count--; 6.65 Silberschatz, Galvin and Gagne 2005 Monitor Implementation The operation x.signal can be implemented as: if (x-count > 0) { next-count++; signal(x-sem); wait(next); next-count--; 6.66 Silberschatz, Galvin and Gagne 2005 33

Synchronization Examples Solaris Windows XP Linux Pthreads 6.67 Silberschatz, Galvin and Gagne 2005 Solaris Synchronization Implements a variety of locks to support multitasking, multithreading (including real-time threads), and multiprocessing Uses adaptive mutexes for efficiency when protecting data from short code segments Uses condition variables and readers-writers locks when longer sections of code need access to data Uses turnstiles to order the list of threads waiting to acquire either an adaptive mutex or reader-writer lock 6.68 Silberschatz, Galvin and Gagne 2005 34

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 either mutexes and semaphores Dispatcher objects may also provide events An event acts much like a condition variable 6.69 Silberschatz, Galvin and Gagne 2005 Linux Synchronization Linux: disables interrupts to implement short critical sections Linux provides: semaphores spin locks 6.70 Silberschatz, Galvin and Gagne 2005 35

Pthreads Synchronization Pthreads API is OS-independent It provides: mutex locks condition variables Non-portable extensions include: read-write locks spin locks 6.71 Silberschatz, Galvin and Gagne 2005 Atomic Transactions System Model Log-based Recovery Checkpoints Concurrent Atomic Transactions 6.72 Silberschatz, Galvin and Gagne 2005 36

System Model Assures that operations happen as a single logical unit of work, in its entirety, or not at all Related to field of database systems Challenge is assuring atomicity despite computer system failures Transaction - collection of instructions or operations that performs single logical function Here we are concerned with changes to stable storage disk Transaction is series of read and write operations Terminated by commit (transaction successful) or abort (transaction failed) operation Aborted transaction must be rolled back to undo any changes it performed 6.73 Silberschatz, Galvin and Gagne 2005 Types of Storage Media Volatile storage information stored here does not survive system crashes Example: main memory, cache Nonvolatile storage Information usually survives crashes Example: disk and tape Stable storage Information never lost Not actually possible, so 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 6.74 Silberschatz, Galvin and Gagne 2005 37

Log-Based Recovery Record to stable storage information about all modifications 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 value <T i starts> written to log when transaction T i starts <T i commits> written when T i commits Log entry must reach stable storage before operation on data occurs 6.75 Silberschatz, Galvin and Gagne 2005 Log-Based Recovery Algorithm Using the log, system can handle any volatile memory errors Undo(T i ) restores value of all data updated by T i Redo(T i ) sets values of all data in transaction T i to new values Undo(T i ) and redo(t i ) must be idempotent Multiple executions must have the same result as one execution If system fails, restore state of all updated data via log If log contains <T i starts> without <T i commits>, undo(t i ) If log contains <T i starts> and <T i commits>, redo(t i ) 6.76 Silberschatz, Galvin and Gagne 2005 38

Checkpoints Log could become long, and recovery could take long Checkpoints shorten log and recovery time. Checkpoint scheme: 1. Output all log records currently in volatile storage to stable storage 2. Output all modified data from volatile to stable storage 3. Output a log record <checkpoint> 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 All other transactions already on stable storage 6.77 Silberschatz, Galvin and Gagne 2005 Concurrent Transactions Must be equivalent to serial execution serializability Could perform all transactions in critical section Inefficient, too restrictive Concurrency-control algorithms provide serializability 6.78 Silberschatz, Galvin and Gagne 2005 39

Serializability Consider two data items A and B Consider Transactions T 0 and T 1 Execute T 0, T 1 atomically Execution sequence called schedule Atomically executed transaction order called serial schedule For N transactions, there are N! valid serial schedules 6.79 Silberschatz, Galvin and Gagne 2005 Schedule 1: T 0 then T 1 6.80 Silberschatz, Galvin and Gagne 2005 40

Nonserial Schedule Nonserial schedule allows overlapped execute Resulting execution not necessarily incorrect Consider schedule S, operations O i, O j Conflict if access same data item, with at least one write If O i, O j consecutive and operations of different transactions & O i and O j don t conflict Then S with swapped order O j O i equivalent to S If S can become S via swapping nonconflicting operations S is conflict serializable 6.81 Silberschatz, Galvin and Gagne 2005 Schedule 2: Concurrent Serializable Schedule 6.82 Silberschatz, Galvin and Gagne 2005 41

Locking Protocol Ensure serializability by associating lock with each data item Follow locking protocol for access control Locks Shared T i has shared-mode lock (S) on item Q, T i can read Q but not write Q Exclusive Ti has exclusive-mode lock (X) on Q, T i can read and write Q Require every transaction on item Q acquire appropriate lock If lock already held, new request may have to wait Similar to readers-writers algorithm 6.83 Silberschatz, Galvin and Gagne 2005 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 6.84 Silberschatz, Galvin and Gagne 2005 42

Timestamp-based Protocols Select order among transactions in advance timestamp-ordering Transaction T i associated with timestamp TS(T i ) before T i starts TS(T i ) < TS(T j ) if Ti entered system before T j TS can be generated from system clock or as logical counter incremented at each entry of transaction Timestamps determine serializability order If TS(T i ) < TS(T j ), system must ensure produced schedule equivalent to serial schedule where T i appears before T j 6.85 Silberschatz, Galvin and Gagne 2005 Timestamp-based Protocol Implementation Data item Q gets two timestamps W-timestamp(Q) largest timestamp of any transaction that executed write(q) successfully R-timestamp(Q) largest timestamp of successful read(q) Updated whenever read(q) or write(q) executed Timestamp-ordering protocol assures any conflicting read and write executed in timestamp order Suppose Ti executes read(q) If TS(T i ) < W-timestamp(Q), Ti needs to read value of Q that was already overwritten read operation rejected and T i rolled back If TS(T i ) W-timestamp(Q) read executed, R-timestamp(Q) set to max(rtimestamp(q), TS(T i )) 6.86 Silberschatz, Galvin and Gagne 2005 43

Timestamp-ordering Protocol Suppose Ti executes write(q) If TS(T i ) < R-timestamp(Q), value Q produced by T i was needed previously and T i assumed it would never be produced Write operation rejected, T i rolled back If TS(T i ) < W-tiimestamp(Q), T i attempting to write obsolete value of Q Write operation rejected and T i rolled back Otherwise, write executed Any rolled back transaction T i is assigned new timestamp and restarted Algorithm ensures conflict serializability and freedom from deadlock 6.87 Silberschatz, Galvin and Gagne 2005 Schedule Possible Under Timestamp Protocol 6.88 Silberschatz, Galvin and Gagne 2005 44

End of Chapter 6 45