Chapter 6: Process Synchronization Joe McCarthy CSS 430: Operating Systems - Process Synchronization1.

Slides:



Advertisements
Similar presentations
Chapter 6: Process Synchronization
Advertisements

Background Concurrent access to shared data can lead to inconsistencies Maintaining data consistency among cooperating processes is critical What is wrong.
5.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Chapter 5: CPU Scheduling.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9 th Edition Chapter 5: Process Synchronization.
Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores.
Synchronization Principles Gordon College Stephen Brinton.
Silberschatz, Galvin and Gagne  Operating System Concepts Chapter 7: Process Synchronization Background The Critical-Section Problem Synchronization.
Chapter 6: Process Synchronization. Outline Background Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores Classic Problems.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th Edition, Feb 8, 2005 Objectives Understand.
Silberschatz, Galvin and Gagne ©2007 Operating System Concepts with Java – 7 th Edition, Nov 15, 2006 Process Synchronization (Or The “Joys” of Concurrent.
Process Synchronization
02/23/2004CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
What we will cover… Process Synchronization Basic Concepts
02/11/2004CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
02/17/2010CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
1 School of Computing Science Simon Fraser University CMPT 300: Operating Systems I Ch 6: Process Synchronization Dr. Mohamed Hefeeda.
Chapter 6: Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Principles Module 6: Synchronization 6.1 Background 6.2 The Critical-Section.
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
02/14/2007CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th Edition, Feb 8, 2005 Module 6: Process Synchronization.
02/19/2007CSCI 315 Operating Systems Design1 Process Synchronization Notice: The slides for this lecture have been largely based on those accompanying.
Adopted from and based on Textbook: Operating System Concepts – 8th Edition, by Silberschatz, Galvin and Gagne Updated and Modified by Dr. Abdullah Basuhail,
Operating Systems CSE 411 CPU Management Oct Lecture 13 Instructor: Bhuvan Urgaonkar.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts – 7 th Edition, Feb 8, 2005 Background Concurrent.
7a.1 Silberschatz, Galvin and Gagne ©2003 Operating System Concepts with Java Module 7a: Classic Synchronization Background The Critical-Section Problem.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Chapter 6: Process Synchronization.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly execution.
6.3 Peterson’s Solution The two processes share two variables: Int turn; Boolean flag[2] The variable turn indicates whose turn it is to enter the critical.
1 Chapter 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Special Machine Instructions for Synchronization Semaphores.
Silberschatz, Galvin and Gagne  Operating System Concepts Chapter 7: Process Synchronization Background The Critical-Section Problem Synchronization.
Silberschatz, Galvin, and Gagne  Applied Operating System Concepts Module 7: Process Synchronization Background The Critical-Section Problem.
Chap 6 Synchronization. Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms.
Chapter 6: Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Synchronization Background The Critical-Section.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Chapter 5: Process Synchronization.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Process Synchronization Background The.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Process Synchronization Background The.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Process Synchronization Background The.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Process Synchronization Background The.
Chapter 6: Process Synchronization. 6.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Module 6: Process Synchronization Background The.
Chapter 6: Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Operating Systems CSE 411 CPU Management Dec Lecture Instructor: Bhuvan Urgaonkar.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts with Java – 8 th Edition Module 6: Process Synchronization.
Process Synchronization. Objectives To introduce the critical-section problem, whose solutions can be used to ensure the consistency of shared data To.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Chapter 6: Process Synchronization.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts – 9 th Edition Chapter 5: Process Synchronization.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Q: 請以實際例子說明 critical section 之意 ? 何謂 race condition? while (true) { /*
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Chapter 6: Process Synchronization.
Chapter 6 Synchronization Dr. Yingwu Zhu. The Problem with Concurrent Execution Concurrent processes (& threads) often access shared data and resources.
6.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Chapter 6: Synchronization Background The Critical-Section Problem Peterson’s.
Process Synchronization
Chapter 5: Process Synchronization
Background on the need for Synchronization
Chapter 5: Process Synchronization
Chapter 5: Process Synchronization
Chapter 6: Process Synchronization
Chapter 6: Process Synchronization
Lecture 9: Process Synchronization
Lecture 9: Process Synchronization
Topic 6 (Textbook - Chapter 5) Process Synchronization
Chapter 6: Process Synchronization
Process Synchronization
Module 7a: Classic Synchronization
Lecture 2 Part 2 Process Synchronization
Critical section problem
Chapter 6: Process Synchronization
Chapter 6: Synchronization Tools
Presentation transcript:

Chapter 6: Process Synchronization Joe McCarthy CSS 430: Operating Systems - Process Synchronization1

Chapter 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization Examples Atomic Transactions 2CSS 430: Operating Systems - Process Synchronization Material derived, in part, from Operating Systems Concepts with Java, 8 th Ed. © 2009 Silberschatz, Galvin & Gagne

Synchronization What is synchronization? CSS 430: Operating Systems - Process Synchronization3

Synchronization What is synchronization? Why do we need to synchronize processes? CSS 430: Operating Systems - Process Synchronization4

Synchronization What is synchronization? Why do we need to synchronize processes? CSS 430: Operating Systems - Process Synchronization5

Circular Buffer (Queue) CSS 430: Operating Systems - Process Synchronization6

Producer-Consumer Problem public void insert () { // Producer E item; while (count == BUFFER_SIZE) ; // busy wait buffer[in] = item; in = (in + 1) % BUFFER_SIZE; ++count; } 7CSS 430: Operating Systems - Process Synchronization public E remove() { // Consumer E item; while (count == 0) ; // busy wait item = buffer[out]; out = (out + 1) % BUFFER_SIZE; --count; return item; }

Producer-Consumer Problem public void insert () { // Producer E item; while (count == BUFFER_SIZE) ; // busy wait buffer[in] = item; in = (in + 1) % BUFFER_SIZE; ++count; } 8CSS 430: Operating Systems - Process Synchronization public E remove() { // Consumer E item; while (count == 0) ; // busy wait item = buffer[out]; out = (out + 1) % BUFFER_SIZE; --count; return item; } LDA COUNT INCA STA COUNT LDA COUNT DECA STA COUNT

Producer-Consumer Problem CSS 430: Operating Systems - Process Synchronization9 import java.util.Date; public class Factory { public static void main( String[] args ) { // create the message queue Channel queue = new MessageQueue (); // create the producer and consumer threads Thread producer = new Thread( new Producer(queue) ); Thread consumer = new Thread( new Consumer(queue) ); // start the threads producer.start(); consumer.start(); } LDA COUNT INCA STA COUNT LDA COUNT DECA STA COUNT [from Chapter 3: Processes]

Producer-Consumer Problem CSS 430: Operating Systems - Process Synchronization10 LDA COUNT INCA STA COUNT LDA COUNT DECA STA COUNT [from Chapter 3: Processes] import java.util.Date; public class Factory { public static void main( String[] args ) { // create the message queue Channel queue = new MessageQueue (); Integer count = new Integer( 0 ); // create the producer and consumer threads Thread producer = new Thread( new Producer(queue, count) ); Thread consumer = new Thread( new Consumer(queue, count) ); // start the threads producer.start(); consumer.start(); }

Producer-Consumer Problem CSS 430: Operating Systems - Process Synchronization11 LDA COUNT INCA STA COUNT LDA COUNT DECA STA COUNT

Producer-Consumer Problem CSS 430: Operating Systems - Process Synchronization12 LDA COUNT INCA LDA COUNT DECA producer consumer STA COUNT LDA COUNT INCA STA COUNT LDA COUNT DECA STA COUNT

Producer-Consumer Problem CSS 430: Operating Systems - Process Synchronization13 LDA COUNT INCA LDA COUNT DECA producer consumer STA COUNT LDA COUNT INCA STA COUNT LDA COUNT DECA STA COUNT What’s the value of count ?

Race Condition CSS 430: Operating Systems - Process Synchronization14 LDA COUNT INCA STA COUNT LDA COUNT DECA STA COUNT Who will get there first?

Race Condition CSS 430: Operating Systems - Process Synchronization15 LDA COUNT INCA STA COUNT LDA COUNT DECA STA COUNT Who will get there first? ace_condition

Critical Section Definition: segment of code that accesses a shared resource Problem: multiple processes have concurrent access to shared resource Solution: prevent multiple processes from having concurrent access to shared resource – No two processes are executing in their critical section at the same time. CSS 430: Operating Systems - Process Synchronization16

General Structure Protocol: – Request entry to critical section – Execute critical section – Exit critical section – Do other stuff (remainder section) CSS 430: Operating Systems - Process Synchronization17

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 CSS 430: Operating Systems - Process Synchronization18

A simple solution Assume: – 2 processes, P 0 & P 1 – 2 shared variables int turn; // if 0, P 0 ’s turn; if 1, P 1 ’s turn boolean flag[2]; // if flag[i], P i wants to enter CS – LOAD (LDA) & STORE (STA) are atomic i.e., assignment statements are indivisible How would you implement this? CSS 430: Operating Systems - Process Synchronization19

Peterson’s Solution CSS 430: Operating Systems - Process Synchronization20 while ( true ) { flag[i] = true; turn = j; while ( flag[j] && turn == j ) ; // busy wait // critical section // … flag[i] = false; // remainder section // … } entry section exit section

Peterson’s Solution CSS 430: Operating Systems - Process Synchronization21 while (true) { flag[i] = true; turn = j; while (flag[j] && turn == j) ; // busy wait // critical section // … flag[i] = false; // remainder section // … } P0P0 while (true) { flag[i] = true; turn = j; while (flag[j] && turn == j) ; // busy wait // critical section // … flag[i] = false; // remainder section // … } P1P1 i = 0, j = 1i = 1, j = 0

Peterson’s Solution CSS 430: Operating Systems - Process Synchronization22 while ( true ) { flag[i] = true; turn = j; while ( flag[j] && turn == j ) ; // busy wait // critical section // … flag[i] = false; // remainder section // … } entry section exit section Software-based solution

Synchronization via Locks CSS 430: Operating Systems - Process Synchronization23 Hardware-based solution

Synchronization via Hardware Disable interrupts during CS – Preempt preemption – Feasible on uniprocessors – What about multiprocessors? Atomic machine instructions – Indivisible (non-interruptable) – Examples: Test & modify word Swap two words CSS 430: Operating Systems - Process Synchronization24

S/W abstraction for H/W Synch. CSS 430: Operating Systems - Process Synchronization25 public class HardwareData { private boolean value = false; public HardwareData( boolean initialValue ) { this.value = initialValue; } public boolean get() { return value; } public void set( boolean newValue ) { this.value = newValue; } public boolean getAndSet( boolean newValue ) { boolean oldValue = this.get(); this.set( newValue ); return oldValue; } public void swap( HardwareData other ) { boolean temp = this.get(); this.set( other.get() ); other.set( temp ); } /usr/apps/CSS430/examples/os-book/ch6/hardware

Using getAndSet() CSS 430: Operating Systems - Process Synchronization26 public class Worker1 implements Runnable { private String name; private HardwareData mutex; public Worker1( String name, HardwareData mutex ) { this.name = name; this.mutex = mutex; } public void run() { // mutex initialized when Worker instantiated while ( true ) { System.out.println( name + " wants to enter CS" ); while ( mutex.getAndSet( true ) ) Thread.yield(); System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); mutex.set( false ); MutualExclusionUtilities.remainderSection( name ); } /usr/apps/CSS430/examples/os-book/ch6/hardware Do you [fore]see any problems?

Using getAndSet() CSS 430: Operating Systems - Process Synchronization27 public class Worker1 implements Runnable { private String name; private HardwareData mutex; public Worker1( String name, HardwareData mutex ) { this.name = name; this.mutex = mutex; } public void run() { // mutex initialized when Worker instantiated while ( true ) { System.out.println( name + " wants to enter CS" ); while ( mutex.getAndSet( true ) ) Thread.yield(); System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); mutex.set( false ); MutualExclusionUtilities.remainderSection( name ); } /usr/apps/CSS430/examples/os-book/ch6/hardware Do you [fore]see any problems? Does this enforce mutual exclusion?

Using swap() CSS 430: Operating Systems - Process Synchronization28 public class Worker2 implements Runnable { private String name; private HardwareData mutex; public Worker2( String name, HardwareData mutex ) { this.name = name; this.mutex = mutex; } public void run() { HardwareData key = new HardwareData( true ); while ( true ) { System.out.println( name + " wants to enter CS" ); key.set( true ); do { mutex.swap( key ); } while ( key.get() ); System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); mutex.set( false ); MutualExclusionUtilities.remainderSection( name ); } /usr/apps/CSS430/examples/os-book/ch6/hardware

Using swap() CSS 430: Operating Systems - Process Synchronization29 public class Worker2 implements Runnable { private String name; private HardwareData mutex; public Worker2( String name, HardwareData mutex ) { this.name = name; this.mutex = mutex; } public void run() { key = new HardwareData( true ); while ( true ) { System.out.println( name + " wants to enter CS" ); key.set( true ); do { mutex.swap( key ); } while ( key.get() ); System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); mutex.set( false ); MutualExclusionUtilities.remainderSection( name ); } Do you [fore]see any new problems? /usr/apps/CSS430/examples/os-book/ch6/hardware

Using swap() CSS 430: Operating Systems - Process Synchronization30 public class Worker2 implements Runnable { private String name; private HardwareData mutex; public Worker2( String name, HardwareData mutex ) { this.name = name; this.mutex = mutex; } public void run() { key = new HardwareData( true ); while ( true ) { System.out.println( name + " wants to enter CS" ); key.set( true ); do { mutex.swap( key ); } while ( key.get() ); System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); mutex.set( false ); MutualExclusionUtilities.remainderSection( name ); } Does not work & play well w/ others /usr/apps/CSS430/examples/os-book/ch6/hardware Do you [fore]see any new problems?

Using swap() CSS 430: Operating Systems - Process Synchronization31 public class Worker2 implements Runnable { private String name; private HardwareData mutex; public Worker2( String name, HardwareData mutex ) { this.name = name; this.mutex = mutex; } public void run() { key = new HardwareData( true ); while ( true ) { System.out.println( name + " wants to enter CS" ); key.set( true ); while ( key.get() ) { Thread.yield(); mutex.swap( key ); } System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); mutex.set( false ); MutualExclusionUtilities.remainderSection( name ); } /usr/apps/CSS430/examples/os-book/ch6/hardware Rewrite using while & yield()

Using AtomicBoolean CSS 430: Operating Systems - Process Synchronization32 public class Worker1a implements Runnable { private String name; private AtomicBoolean mutex; public Worker1a( String name, AtomicBoolean mutex ) { this.name = name; this.mutex = mutex; } public void run() { // mutex initialized when Worker instantiated while ( true ) { System.out.println( name + " wants to enter CS" ); while ( mutex.getAndSet( true ) ) Thread.yield(); System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); mutex.set( false ); MutualExclusionUtilities.remainderSection( name ); } /usr/apps/CSS430/examples/os-book/ch6/hardware

AtomicBooleanFactory CSS 430: Operating Systems - Process Synchronization33 import java.util.concurrent.atomic.AtomicBoolean; public class AtomicBooleanFactory { public static void main( String args[] ) { AtomicBoolean lock = new AtomicBoolean( false ); Thread[] worker = new Thread[5]; for ( int i = 0; i < 5; i++ ) { worker[i] = new Thread( new Worker1a( String.format( "worker %d", i ), lock ) ); worker[i].start(); } /usr/apps/CSS430/examples/os-book/ch6/hardware

Semaphores Software-based synchronization mechanism – Avoids busy waiting Semaphore S – integer variable – Value  # of shared resources available – Binary (1), aka mutex locks, or Counting (> 1) [Only] 2 indivisible operations modify S: – acquire() & release() – Originally: P() [proberen, “test”] & V() [verhogen, “increment”] CSS 430: Operating Systems - Process Synchronization34

Semaphores Indivisible testing & modification of value CSS 430: Operating Systems - Process Synchronization35

Semaphores for Synchronization Critical section protection, other synchronization CSS 430: Operating Systems - Process Synchronization36 Process P 0 : Process P 1 :

getAndSet vs. Semaphores CSS 430: Operating Systems - Process Synchronization37 private AtomicBoolean mutex; … while ( mutex.getAndSet( true ) ) Thread.yield(); // critical section mutex.set( false ); // remainder section …

Busy waiting vs. Blocking CSS 430: Operating Systems - Process Synchronization38

Busy waiting vs. Blocking CSS 430: Operating Systems - Process Synchronization39

Blocking & Waking up CSS 430: Operating Systems - Process Synchronization40

A Semaphore Implementation CSS 430: Operating Systems - Process Synchronization41 public class Semaphore { private int value; public Semaphore( int initialValue ) { this.value = initialValue; } public synchronized void acquire() { while ( value <= 0 ) { try { wait(); } catch ( InterruptedException e ) { } value--; } public synchronized void release() { ++value; notify(); } /usr/apps/CSS430/examples/os-book/ch6/semaphores

Java Thread Transitions CSS 430: Operating Systems - Process Synchronization42 er+9.+Threads/9.5+Thread+Transitions/

AtomicBoolean vs. Semaphore CSS 430: Operating Systems - Process Synchronization43 public class Worker1a implements Runnable { private String name; private AtomicBoolean mutex; public Worker1a( String name, AtomicBoolean mutex ) { this.name = name; this.mutex = mutex; } public void run() { // mutex initialized when Worker instantiated while ( true ) { System.out.println( name + " wants to enter CS" ); while ( mutex.getAndSet( true ) ) Thread.yield(); System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); mutex.set( false ); MutualExclusionUtilities.remainderSection( name ); } /usr/apps/CSS430/examples/os-book/ch6/hardware

A Semaphore Example CSS 430: Operating Systems - Process Synchronization44 import java.util.concurrent.Semaphore; public class Worker implements Runnable { private Semaphore sem; private String name; public Worker( String name, Semaphore sem ) { this.name = name; this.sem = sem; } public void run() { while ( true ) { sem.acquire(); System.out.println( name + " is in critical section" ); MutualExclusionUtilities.criticalSection( name ); System.out.println( name + " is out of critical section" ); sem.release(); MutualExclusionUtilities.remainderSection( name ); } /usr/apps/CSS430/examples/os-book/ch6/semaphores

A Semaphore Example CSS 430: Operating Systems - Process Synchronization45 import java.util.concurrent.Semaphore; public class SemaphoreFactory { public static void main( String args[] ) { Semaphore sem = new Semaphore( 1 ); Thread[] bee = new Thread[5]; for ( int i = 0; i < 5; i++ ) bee[i] = new Thread( new Worker( String.format( "worker %d", i), sem ) ); for ( int i = 0; i < 5; i++ ) bee[i].start(); } /usr/apps/CSS430/examples/os-book/ch6/semaphores

Deadlock & 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 Starvation – indefinite blocking. A process may never be removed from the semaphore queue in which it is suspended. 46CSS 430: Operating Systems - Process Synchronization

Classic Synchronization Problems Representative of large class of problems Used to test prospective solutions Examples: – Bounded Buffer Problem – Readers and Writers Problem – Dining Philosophers Problem CSS 430: Operating Systems - Process Synchronization47

Bounded Buffer Problem N buffers, each can hold one item Solution: 3 semaphores – mutex (1): provide mutual exclusion – full (0): # of full buffers – empty (N): # of empty buffers CSS 430: Operating Systems - Process Synchronization48 /usr/apps/CSS430/examples/os- book/ch6/semaphores/boundedbuffer

Bounded Buffer Problem 49CSS 430: Operating Systems - Process Synchronization

Bounded Buffer insert() 50CSS 430: Operating Systems - Process Synchronization

Bounded Buffer remove() 51CSS 430: Operating Systems - Process Synchronization

Bounded Buffer producer 52CSS 430: Operating Systems - Process Synchronization import java.util.Date; public class Producer implements Runnable { private Buffer buffer; public Producer( Buffer buffer ) { this.buffer = buffer; } public void run() { Date message; while ( true ) { // produce an item & enter it into the buffer message = new Date(); System.out.printf( "> Producer wants to insert\n" ); buffer.insert( message ); System.out.printf( "< Producer has inserted\n" ); }

Bounded Buffer consumer 53CSS 430: Operating Systems - Process Synchronization import java.util.*; public class Consumer implements Runnable { private Buffer buffer; // was public Consumer( Buffer buffer ) { this.buffer = buffer; } public void run() { Date message; while ( true ) { SleepUtilities.nap(); // consume an item from the buffer System.out.printf( "> Consumer wants to consume\n" ); message = buffer.remove(); System.out.printf( "< Consumer has consumed '%s'\n", message ); }

Bounded Buffer factory 54CSS 430: Operating Systems - Process Synchronization

Readers & Writers Problem Data set shared among concurrent processes – Readers: only read the data; do not modify it – Writers: can both read and write Multiple readers can concurrently read If one writer has access, no one else can have access Problem: if reader(s) and writer(s) both want access, who gets to go (& when)? CSS 430: Operating Systems - Process Synchronization55

Readers & Writers Problem Potential solutions? CSS 430: Operating Systems - Process Synchronization56

Readers & Writers Problem Potential solutions: – New writers waits for readers – New readers wait for writers Any problems with these “solutions”? CSS 430: Operating Systems - Process Synchronization57

Readers & Writers Problem Potential solutions: – New writers waits for readers – New readers wait for writers Any problems with these “solutions”? – starvation Approach: – Database – Integer readerCount (0): # of current readers – Semaphore mutex (1): protect readerCount – Semaphore db (1): protect database updates CSS 430: Operating Systems - Process Synchronization58 /usr/apps/CSS430/examples/os- book/ch6/semaphores/readwrite

Readers & Writers Problem Interface for read-write locks CSS 430: Operating Systems - Process Synchronization59

Readers & Writers Problem The structure of a Writer CSS 430: Operating Systems - Process Synchronization60

Readers & Writers Problem The structure of a Reader CSS 430: Operating Systems - Process Synchronization61

The database Readers & Writers Problem CSS 430: Operating Systems - Process Synchronization62

Readers & Writers Problem Reader methods CSS 430: Operating Systems - Process Synchronization63

Readers & Writers Problem Writer methods CSS 430: Operating Systems - Process Synchronization64

Dining Philosophers Problem Philosopher’s Life: a cycle of – Thinking (no interaction) – Getting Hungry Pick up one chopstick at a time – Eating Eat Put down both chopsticks CSS 430: Operating Systems - Process Synchronization65

Dining Philosophers Problem Philosopher’s Life: a cycle of – Thinking (no interaction) – Getting Hungry Pick up one chopstick at a time – Eating Eat Put down both chopsticks Potential problems? CSS 430: Operating Systems - Process Synchronization66

Dining Philosophers Problem Philosopher’s Life: a cycle of – Thinking (no interaction) – Getting Hungry Pick up one chopstick at a time – Eating Eat Put down both chopsticks Potential problems: – Starvation and Deadlock CSS 430: Operating Systems - Process Synchronization67

Dining Philosophers Problem Philosopher’s Life: a cycle of – Thinking (no interaction) – Getting Hungry Pick up one chopstick at a time – Eating Eat Put down both chopsticks Potential problems: – Starvation and Deadlock CSS 430: Operating Systems - Process Synchronization68 Edsger Wybe Dijkstra

Dining Philosophers Problem Potential solutions? CSS 430: Operating Systems - Process Synchronization69

Dining Philosophers Problem Potential solutions (deadlock): – Restrict # of philosophers at table – Allow pickup only if both available – Asymmetry: Odd philosopher pick up left, then right Even philosopher pick up right, then left Note: deadlock-free != starvation-free Approach: – Bowl of rice (data set) – Semaphore chopStick [5] initialized to 1 CSS 430: Operating Systems - Process Synchronization70

Dining Philosophers Problem The structure of Philosopher i: CSS 430: Operating Systems - Process Synchronization71

Problems with Semaphores Might arise from – Honest programming error – Intentionally uncooperative programming CSS 430: Operating Systems - Process Synchronization72 mutex.release(); // critical // section mutex.acquire(); // critical // section mutex.acquire(); // critical // section // … // critical // section mutex.release()

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 73CSS 430: Operating Systems - Process Synchronization

Syntax of a Monitor 74CSS 430: Operating Systems - Process Synchronization

Schematic view of a Monitor 75CSS 430: Operating Systems - Process Synchronization

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 () 76CSS 430: Operating Systems - Process Synchronization

Monitor with Condition Variables CSS 430: Operating Systems - Process Synchronization77

Solution to Dining Philosophers 78CSS 430: Operating Systems - Process Synchronization

Solution to Dining Philosophers CSS 430: Operating Systems - Process Synchronization79 Each philosopher I invokes the operations takeForks(i) & returnForks(i) in the following sequence: dp.takeForks (i) EAT dp.returnForks (i)

Java Synchronization Java provides synchronization at the language-level – “Thread-safe” Each Java object has an implicit lock – It is acquired by invoking a synchronized method – It is released by exiting the synchronized method – Normally or abnormally (via exception) Threads waiting to acquire the object lock are placed in the entry set for the lock Threads waiting to re-acquire a previously acquired object lock are placed in the wait set for the lock CSS 430: Operating Systems - Process Synchronization80

Java Synchronization When a thread invokes wait(): 1. It releases the object lock 2. Its state is set to Blocked 3. It is placed in the wait set for the object When a thread invokes notify(): 1. A thread T from the wait set is selected 2. T is moved from the wait set to the entry set 3. The state of T is set to Runnable CSS 430: Operating Systems - Process Synchronization81

Java Synchronization: insert() CSS 430: Operating Systems - Process Synchronization82

Java Synchronization: remove() CSS 430: Operating Systems - Process Synchronization83

Java Synchronization: Bounded Buffer CSS 430: Operating Systems - Process Synchronization84

Java Synchronization notify() may not notify the correct thread! 85CSS 430: Operating Systems - Process Synchronization

Java Synchronization The call to notify() arbitrarily selects a single thread from the wait set. It is possible the selected thread is in fact not waiting upon the condition for which it was notified. The call notifyAll() selects all threads in the wait set and moves them to the entry set. In general, notifyAll() is a more conservative strategy than notify(). CSS 430: Operating Systems - Process Synchronization86

CSS 430: Operating Systems - Process Synchronization87

Java Synchronization: Readers & Writers CSS 430: Operating Systems - Process Synchronization88

Java Synchronization: Readers & Writers CSS 430: Operating Systems - Process Synchronization89

Java Synchronization: Readers & Writers CSS 430: Operating Systems - Process Synchronization90

Block Synchronization Rather than synchronizing an entire method, block synchronization allows blocks of code to be declared as synchronized CSS 430: Operating Systems - Process Synchronization91

Block Synchronization Block synchronization using wait()/notify() CSS 430: Operating Systems - Process Synchronization92

Concurrency Features in Java 5 Concurrency features before Java 5: – synchronized methods & blocks – wait(), notify(), notifyAll() Concurrency classes added to Java 5: – Semaphore – ReentrantLock – Condition Concurrency Tutorial: – urrency/ urrency/ CSS 430: Operating Systems - Process Synchronization93

Java 5: Semaphore CSS 430: Operating Systems - Process Synchronization94

CSS 430: Operating Systems - Process Synchronization95

Java 5: ReentrantLock CSS 430: Operating Systems - Process Synchronization96

CSS 430: Operating Systems - Process Synchronization97

Java 5: Condition A Condition variable is created by – Creating a RentrantLock – Invoking its newCondition() method – Assigning result to a Condition variable Once this is done, it is possible to invoke – await() – signal() CSS 430: Operating Systems - Process Synchronization98

Java Condition Class CSS 430: Operating Systems - Process Synchronization99

Concurrency Features in Java 5 100CSS 430: Operating Systems - Process Synchronization