CS 333 Introduction to Operating Systems. Class 6 Monitors and Message Passing. Jonathan Walpole Computer Science Portland State University

Similar documents
CS510 Operating System Foundations. Jonathan Walpole

Administrivia. Assignments 0 & 1 Class contact for the next two weeks Next week. Following week

Interprocess Communication and Synchronization

Process Synchronization

Classic Problems of Synchronization

5 Classical IPC Problems

CS533 Concepts of Operating Systems. Jonathan Walpole

Lecture 6 (cont.): Semaphores and Monitors

CS 333 Introduction to Operating Systems. Class 4 Concurrent Programming and Synchronization Primitives

Semaphores. To avoid busy waiting: when a process has to wait, it will be put in a blocked queue of processes waiting for the same event

Semaphores. Semaphores. Semaphore s operations. Semaphores: observations

Operating Systems CMPSC 473. Synchronization February 26, Lecture 12 Instructor: Trent Jaeger

CS450 OPERATING SYSTEMS FINAL EXAM ANSWER KEY

Process Management And Synchronization

CSE 153 Design of Operating Systems

Lecture 7: CVs & Scheduling

CS3502 OPERATING SYSTEMS

Chapter 6: Process Synchronization. Operating System Concepts 8 th Edition,

Silberschatz and Galvin Chapter 6

CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives

Semaphores (by Dijkstra)

Introduction to OS Synchronization MOS 2.3

Operating Systems ECE344

Concurrency and Synchronisation

Reminder from last time

Opera&ng Systems ECE344

Concurrency. Chapter 5

Chapter 6: Process Synchronization

Semaphores and Monitors: High-level Synchronization Constructs

Concurrency and Synchronisation

CS370: System Architecture & Software [Fall 2014] Dept. Of Computer Science, Colorado State University

Operating Systems. User OS. Kernel & Device Drivers. Interface Programs. Interprocess Communication (IPC)

Chapter 7: Process Synchronization!

CSE 120 Principles of Operating Systems Spring 2016

CSE 120 Principles of Operating Systems Spring 2016

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Semaphores. A semaphore is an object that consists of a. methods (e.g., functions): signal and wait. semaphore. method signal. counter.

Chapter 5 Concurrency: Mutual Exclusion and Synchronization

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2.

Synchronization II. Today. ! Condition Variables! Semaphores! Monitors! and some classical problems Next time. ! Deadlocks

CS 318 Principles of Operating Systems

Lecture 6. Process Synchronization

CS 537 Lecture 8 Monitors. Thread Join with Semaphores. Dining Philosophers. Parent thread. Child thread. Michael Swift

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T

Threads. Concurrency. What it is. Lecture Notes Week 2. Figure 1: Multi-Threading. Figure 2: Multi-Threading

Process Synchronization

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6.

Chapter 6: Process Synchronization

PROCESS SYNCHRONIZATION

Puzzle: Write synchronization code for oxygen and hydrogen molecules that enforces these constraints.

Operating systems and concurrency (B08)

Synchronization 1. Synchronization

CS 318 Principles of Operating Systems

Interprocess Communication By: Kaushik Vaghani

Semaphores. Blocking in semaphores. Two types of semaphores. Example: Bounded buffer problem. Binary semaphore usage

Introduction to Operating Systems

Concurrency Principles

Concurrency: Mutual Exclusion and Synchronization - Part 2

Process Synchronization

Real-Time Operating Systems M. 5. Process Synchronization

CHAPTER 6: PROCESS SYNCHRONIZATION

1 Process Coordination

Summary Semaphores. Passing the Baton any await statement. Synchronisation code not linked to the data

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018

CSE 451: Operating Systems Spring Module 10 Semaphores, Condition Variables, and Monitors

More Synchronization; Concurrency in Java. CS 475, Spring 2018 Concurrent & Distributed Systems

CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14. The dining philosophers problem

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

Roadmap. Readers-Writers Problem. Readers-Writers Problem. Readers-Writers Problem (Cont.) Dining Philosophers Problem.

Roadmap. Tevfik Ko!ar. CSC Operating Systems Fall Lecture - XI Deadlocks - II. Louisiana State University

Roadmap. Bounded-Buffer Problem. Classical Problems of Synchronization. Bounded Buffer 1 Semaphore Soln. Bounded Buffer 1 Semaphore Soln. Tevfik Ko!

Process Synchronization

IT 540 Operating Systems ECE519 Advanced Operating Systems

Back to synchronization

CS370 Operating Systems

Chapter 7: Process Synchronization. Background. Illustration

COMP 346 WINTER Tutorial 5 MONITORS

Event Counts: Producer-Consumer. Sequencers. Concurrent Systems 8L for Part IB Handout 2. Event Counts & Sequencers. Dr.

Yet another synchronization problem

CSE 451: Operating Systems Winter Synchronization. Gary Kimura

Concurrency and Synchronisation. Leonid Ryzhyk

CS 318 Principles of Operating Systems

Lesson 6: Process Synchronization

Sections 01 (11:30), 02 (16:00), 03 (8:30) Ashraf Aboulnaga & Borzoo Bonakdarpour

Operating Systems. Synchronization, part 3 Monitors, classical sync. problems

Synchronization II. q Condition Variables q Semaphores and monitors q Some classical problems q Next time: Deadlocks

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions

Dealing with Issues for Interprocess Communication

Chapter 6: Process Synchronization

Synchronization 1. Synchronization

CS Operating Systems

CS Operating Systems

Chapter 6: Process Synchronization. Operating System Concepts 9 th Edit9on

Chapter 7: Process Synchronization. Background

Process Synchronization: Semaphores. CSSE 332 Operating Systems Rose-Hulman Institute of Technology

Lecture Topics. Announcements. Today: Concurrency (Stallings, chapter , 5.7) Next: Exam #1. Self-Study Exercise #5. Project #3 (due 9/28)

Distributed Real-Time Control Systems. Lecture 21 Condition Variables Typical ConcurrencyProblems

Process Coordination

Concept of a process

Transcription:

CS 333 Introduction to Operating Systems Class 6 Monitors and Message Passing Jonathan Walpole Computer Science Portland State University 1

But first Continuation of Class 5 Classical Synchronization Problems 2

Producer consumer problem Also known as the bounded buffer problem InP Producer Producer and consumer are separate threads 8 Buffers OutP Consumer 3

Does this solution work? Global variables semaphore full_buffs = 0; semaphore empty_buffs = n; char buff[n]; int InP, OutP; 0 thread producer { 1 while(1){ 2 // Produce char c... 3 down(empty_buffs) 4 buf[inp] = c 5 InP = InP + 1 mod n 6 up(full_buffs) 7 } 8 } 0 thread consumer { 1 while(1){ 2 down(full_buffs) 3 c = buf[outp] 4 OutP = OutP + 1 mod n 5 up(empty_buffs) 6 // Consume char... 7 } 8 } 4

Producer consumer problem What is the shared state in the last solution? Does it apply mutual exclusion? If so, how? InP Producer Producer and consumer are separate threads 8 Buffers OutP Consumer 5

Problems with solution What if we have multiple producers and multiple consumers? Producer-specific and consumer-specific data becomes shared We need to define and protect critical sections 6

Dining philosophers problem Five philosophers sit at a table One fork/chopstick between each philosopher need two to eat Each philosopher is modeled with a thread while(true) { Think(); Grab first fork; Grab second fork; Eat(); Put down first fork; Put down second fork; } Why do they need to synchronize? How should they do it? 7

Is this a valid solution? #define N 5 Philosopher() { while(true) { Think(); take_fork(i); take_fork((i+1)% N); Eat(); put_fork(i); put_fork((i+1)% N); } } 8

Problems Holding one fork while you wait for the other can lead to deadlock! You should not hold on to a fork unless you can get both Is there a deterministic, deadlock-free, starvationfree solution to doing this? 9

Working towards a solution #define N 5 Philosopher() { while(true) { Think(); take_fork(i); take_fork((i+1)% N); Eat(); put_fork(i); put_fork((i+1)% N); } } take_forks(i) put_forks(i) 10

Working towards a solution #define N 5 Philosopher() { while(true) { Think(); take_forks(i); Eat(); put_forks(i); } } 11

Picking up forks int state[n] semaphore mutex = 1 semaphore sem[i] take_forks(int i) { wait(mutex); state [i] = HUNGRY; test(i); signal(mutex); wait(sem[i]); } // only called with mutex set! test(int i) { if (state[i] == HUNGRY && state[left]!= EATING && state[right]!= EATING){ state[i] = EATING; signal(sem[i]); } } 12

Putting down forks int state[n] semaphore mutex = 1 semaphore sem[i] put_forks(int i) { wait(mutex); state [i] = THINKING; test(left); test(right); signal(mutex); } // only called with mutex set! test(int i) { if (state[i] == HUNGRY && state[left]!= EATING && state[right]!= EATING){ state[i] = EATING; signal(sem[i]); } } 13

Dining philosophers Is the previous solution correct? What does it mean for it to be correct? How could you generate output to help detect common problems? What would a race condition look like? What would deadlock look like? What would starvation look like? 14

The sleeping barber problem 15

The sleeping barber problem Barber: While there are customers waiting for a hair cut put one in the barber chair and cut their hair When done move to the next customer else go to sleep, until a customer comes in Customer: If barber is asleep wake him up for a haircut If someone is getting a haircut wait for the barber to become free by sitting in a chair If all chairs are all full, leave the barbershop 16

Designing a solution How will we model the barber(s) and customers? What state variables do we need?.. and which ones are shared?. and how will we protect them? How will the barber sleep? How will the barber wake up? How will customers wait? How will they proceed? What problems do we need to look out for? 17

Is this a good solution? const CHAIRS = 5 var customers: Semaphore barbers: Semaphore lock: Mutex numwaiting: int = 0 Barber Thread: while true Wait(customers) Lock(lock) numwaiting = numwaiting-1 Signal(barbers) Unlock(lock) CutHair() endwhile Customer Thread: Lock(lock) if numwaiting < CHAIRS numwaiting = numwaiting+1 Signal(customers) Unlock(lock) Wait(barbers) GetHaircut() else -- give up & go home Unlock(lock) endif 18

The readers and writers problem Multiple readers and writers want to access a database (each one is a thread) Multiple readers can proceed concurrently No race condition if nobody is modifying data Writers must synchronize with readers and other writers only one writer at a time! when someone is writing, there must be no readers! Goals: Maximize concurrency. Prevent starvation. 19

Designing a solution How will we model the readers and writers? What state variables do we need?.. and which ones are shared?. and how will we protect them? How will the writers wait? How will the writers wake up? How will readers wait? How will the readers wake up? What problems do we need to look out for? 20

Is this a valid solution to readers & writers? var mut: Mutex = unlocked db: Semaphore = 1 rc: int = 0 Writer Thread: while true...remainder Section... Wait(db)...Write shared data... Signal(db) endwhile Reader Thread: while true Lock(mut) rc = rc + 1 if rc == 1 Wait(db) endif Unlock(mut)... Read shared data... Lock(mut) rc = rc - 1 if rc == 0 Signal(db) endif Unlock(mut)... Remainder Section... endwhile 21

Readers and writers solution Does the previous solution have any problems? is it fair? can any threads be starved? If so, how could this be fixed? 22

Monitors 23

Monitors It is difficult to produce correct programs using semaphores correct ordering of wait and signal is tricky! avoiding race conditions and deadlock is tricky! boundary conditions are tricky! Can we get the compiler to generate the correct semaphore code for us? what are suitable higher level abstractions for synchronization? 24

Monitors Related shared objects are collected together Compiler enforces encapsulation/mutual exclusion Encapsulation: Local data variables are accessible only via the monitor s entry procedures (like methods) Mutual exclusion A monitor has an associated mutex lock Threads must acquire the monitor s mutex lock before invoking one of its procedures 25

Monitors and condition variables But we need two flavors of synchronization Mutual exclusion Only one at a time in the critical section Handled by the monitor s mutex Condition synchronization Wait until a certain condition holds Signal waiting threads when the condition holds 26

Monitors and condition variables Condition variables (cv) for use within monitors cv.wait(mon-mutex) thread blocked (queued) until condition holds Must not block while holding mutex! monitor mutex must be released! cv.signal() signals the condition and unblocks (dequeues) a thread 27

Monitor structures shared data condition variables y x monitor entry queue Local to monitor (Each has an associated list of waiting threads) entry methods List of threads waiting to enter the monitor local methods Can be called from outside the monitor. Only one active at any moment. initialization code 28

Monitor example for mutual exclusion process Producer begin loop <produce char c > BoundedBuffer.deposit(c) end loop end Producer process Consumer begin loop BoundedBuffer.remove(c) <consume char c > end loop end Consumer monitor: BoundedBuffer var buffer :...; nextin, nextout :... ; entry deposit(c: char) begin... end entry remove(var c: char) begin... end end BoundedBuffer 29

Observations That s much simpler than the semaphore-based solution to producer/consumer (bounded buffer)! but where is the mutex? and what do the bodies of the monitor procedures look like? 30

Monitor example with condition variables monitor : BoundedBuffer var buffer : array[0..n-1] of char nextin,nextout : 0..n-1 := 0 fullcount : 0..n := 0 notempty, notfull : condition entry deposit(c:char) entry remove(var c: char) begin begin if (fullcount = n) then if (fullcount = n) then wait(notfull) wait(notempty) end if end if buffer[nextin] := c c := buffer[nextout] nextin := nextin+1 mod n nextout := nextout+1 mod n fullcount := fullcount+1 fullcount := fullcount-1 signal(notempty) signal(notfull) end deposit end remove end BoundedBuffer 31

Condition variables Condition variables allow processes to synchronize based on some state of the monitor variables. 32

Condition variables in producer/consumer NotFull condition NotEmpty condition Operations Wait() and Signal() allow synchronization within the monitor When a producer thread adds an element... A consumer may be sleeping Need to wake the consumer... Signal 33

Condition synchronization semantics Only one thread can be executing in the monitor at any one time. Scenario: Thread A is executing in the monitor Thread A does a signal waking up thread B What happens now? Signaling and signaled threads can not both run! so which one runs, which one blocks, and on what queue? 34

Monitor design choices Condition variables introduce a problem for mutual exclusion only one process active in the monitor at a time, so what to do when a process is unblocked on signal? must not block holding the mutex, so what to do when a process blocks on wait? 35

Monitor design choices Choices when A signals a condition that unblocks B A waits for B to exit the monitor or block again B waits for A to exit the monitor or block Signal causes A to immediately exit the monitor or block ( but awaiting what condition?) Choices when A signals a condition that unblocks B & C B is unblocked, but C remains blocked C is unblocked, but B remains blocked Both B & C are unblocked and compete for the mutex? Choices when A calls wait and blocks a new external process is allowed to enter but which one? 36

Option 1: Hoare semantics What happens when a Signal is performed? signaling thread (A) is suspended signaled thread (B) wakes up and runs immediately Result: B can assume the condition is now true/satisfied Hoare semantics give strong guarantees Easier to prove correctness When B leaves monitor, A can run. A might resume execution immediately... or maybe another thread (C) will slip in! 37

Option 2: MESA Semantics (Xerox PARC) What happens when a Signal is performed? the signaling thread (A) continues. the signaled thread (B) waits. when A leaves monitor, then B runs. Issue: What happens while B is waiting? can the condition that caused A to generate the signal be changed before B runs? In MESA semantics a signal is more like a hint Requires B to recheck the condition on which it waited to see if it can proceed or must wait some more 38

Code for the deposit entry routine monitor BoundedBuffer var buffer: array[n] of char nextin, nextout: int = 0 cntfull: int = 0 notempty: Condition notfull: Condition entry deposit(c: char) if cntfull == N notfull.wait() endif buffer[nextin] = c nextin = (nextin+1) mod N cntfull = cntfull + 1 notempty.signal() endentry Hoare Semantics entry remove()... endmonitor 39

Code for the deposit entry routine monitor BoundedBuffer var buffer: array[n] of char nextin, nextout: int = 0 cntfull: int = 0 notempty: Condition notfull: Condition entry deposit(c: char) while cntfull == N notfull.wait() endwhile buffer[nextin] = c nextin = (nextin+1) mod N cntfull = cntfull + 1 notempty.signal() endentry MESA Semantics entry remove()... endmonitor 40

Code for the remove entry routine monitor BoundedBuffer var buffer: array[n] of char nextin, nextout: int = 0 cntfull: int = 0 notempty: Condition notfull: Condition entry deposit(c: char)... entry remove() if cntfull == 0 notempty.wait() endif c = buffer[nextout] nextout = (nextout+1) mod N cntfull = cntfull - 1 notfull.signal() endentry Hoare Semantics endmonitor 41

Code for the remove entry routine monitor BoundedBuffer var buffer: array[n] of char nextin, nextout: int = 0 cntfull: int = 0 notempty: Condition notfull: Condition entry deposit(c: char)... entry remove() while cntfull == 0 notempty.wait() endwhile c = buffer[nextout] nextout = (nextout+1) mod N cntfull = cntfull - 1 notfull.signal() endentry MESA Semantics endmonitor 42

Hoare Semantics What happens when a Signal is performed? The signaling thread (A) is suspended. The signaled thread (B) wakes up and runs immediately. B can assume the condition is now true/satisfied From the original Hoare Paper: No other thread can intervene [and enter the monitor] between the signal and the continuation of exactly one waiting thread. If more than one thread is waiting on a condition, we postulate that the signal operation will reactivate the longest waiting thread. This gives a simple neutral queuing discipline which ensures that every waiting thread will eventually get its turn. 43

Implementing Hoare Semantics Thread A holds the monitor lock Thread A signals a condition that thread B was waiting on Thread B is moved back to the ready queue? B should run immediately Thread A must be suspended... the monitor lock must be passed from A to B When B finishes it releases the monitor lock Thread A must re-acquire the lock A is blocked, waiting to re-aquire the lock 44

Implementing Hoare Semantics Problem: Possession of the monitor lock must be passed directly from A to B and then eventually back to A 45

Implementing Hoare Semantics Implementation Ideas: Consider a signaled thread like B to be urgent after A releases the monitor lock Thread C trying to gain initial entry to the monitor is not urgent Consider two wait lists associated with each MonitorLock (so now this is not exactly a mutex) UrgentlyWaitingThreads NonurgentlyWaitingThreads Want to wake up urgent threads first, if any Alternatively, B could be added to the front of the monitor lock queue 46

Implementing Hoare Semantics Recommendation for Project 4 implementation: Do not modify the mutex methods provided, because future code will use them Create new classes: MonitorLock -- similar to Mutex HoareCondition -- similar to Condition 47

Brinch-Hansen Semantics Hoare Semantics On signal, allow signaled process to run Upon its exit from the monitor, signaling process continues. Brinch-Hansen Semantics Signaler must immediately exit following any invocation of signal Restricts the kind of solutions that can be written but monitor implementation is easier 48

Review of a Practical Concurrent Programming Issue Reentrant Functions 49

Reentrant code A function/method is said to be reentrant if... A function that has been invoked may be invoked again before the first invocation has returned, and will still work correctly In the context of concurrent programming... A reentrant function can be executed simultaneously by more than one thread, with no ill effects 50

Reentrant Code Consider this function... var count: int = 0 function GetUnique () returns int count = count + 1 return count endfunction What if it is executed by different threads concurrently? 51

Reentrant Code Consider this function... var count: int = 0 function GetUnique () returns int count = count + 1 return count endfunction What if it is executed by different threads concurrently? The results may be incorrect! This routine is not reentrant! 52

When is code reentrant? Some variables are local -- to the function/method/routine global -- sometimes called static Access to local variables? A new stack frame is created for each invocation Each thread has its own stack What about access to global variables? Must use synchronization! 53

Does this work? var count: int = 0 mylock: Mutex function GetUnique () returns int mylock.lock() count = count + 1 mylock.unlock() return count endfunction 54

What about this? var count: int = 0 mylock: Mutex function GetUnique () returns int mylock.lock() count = count + 1 return count mylock.unlock() endfunction 55

Making this function reentrant var count: int = 0 mylock: Mutex function GetUnique () returns int var i: int mylock.lock() count = count + 1 i = count mylock.unlock() return i endfunction 56

Message Passing 57

Message Passing Interprocess Communication via shared memory across machine boundaries Message passing can be used for synchronization or general communication Processes use send and receive primitives receive can block (like waiting on a Semaphore) send unblocks a process blocked on receive (just as a signal unblocks a waiting process) 58

Producer-consumer with message passing The basic idea: After producing, the producer sends the data to consumer in a message The system buffers messages The producer can out-run the consumer The messages will be kept in order But how does the producer avoid overflowing the buffer? After consuming the data, the consumer sends back an empty message A fixed number of messages (N=100) The messages circulate back and forth. 59

Producer-consumer with message passing const N = 100 -- Size of message buffer var em: char for i = 1 to N -- Get things started by Send (producer, &em) -- sending N empty messages endfor thread consumer var c, em: char while true Receive(producer, &c) Send(producer, &em) // Consume char... endwhile end -- Wait for a char -- Send empty message back 60

Producer-consumer with message passing thread producer var c, em: char while true // Produce char c... Receive(consumer, &em) Send(consumer, &c) endwhile end -- Wait for an empty msg -- Send c to consumer 61

Design choices for message passing Option 1: Mailboxes System maintains a buffer of sent, but not yet received, messages Must specify the size of the mailbox ahead of time Sender will be blocked if the buffer is full Receiver will be blocked if the buffer is empty 62

Design choices for message passing Option 2: No buffering If Send happens first, the sending thread blocks If Receiver happens first, the receiving thread blocks Sender and receiver must Rendezvous (ie. meet) Both threads are ready for the transfer The data is copied / transmitted Both threads are then allowed to proceed 63

Barriers Processes approaching a barrier All processes but one blocked at barrier Last process arrives; all are let through 64

Quiz What is the difference between a monitor and a semaphore? Why might you prefer one over the other? How do the wait/signal methods of a condition variable differ from the wait/signal methods of a semaphore? What is the difference between Hoare and Mesa semantics for condition variables? What implications does this difference have for code surrounding a wait() call? 65