CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004

Similar documents
Page 1. CS162 Operating Systems and Systems Programming Lecture 8. Readers-Writers Language Support for Synchronization

Lecture #10: Synchronization wrap up

CS162 Operating Systems and Systems Programming Lecture 8. Readers-Writers Language Support for Synchronization

February 23 rd, 2015 Prof. John Kubiatowicz

CS162 Operating Systems and Systems Programming Lecture 7 Semaphores, Conditional Variables, Deadlocks"

Page 1. Goals for Today" Recap: Monitors" CS162 Operating Systems and Systems Programming Lecture 7. Semaphores, Conditional Variables, Deadlocks"

Concurrent Programming Issues & Readers/Writers

Semaphores and Monitors: High-level Synchronization Constructs

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables

Page 1. Goals for Today" Recap: Readers/Writers Problem" W

Page 1. CS162 Operating Systems and Systems Programming Lecture 9. Tips for Working in a Project Team/ Cooperating Processes and Deadlock

Midterm 1, CSE 451, Winter 2001 (Prof. Steve Gribble)

What's wrong with Semaphores?

CS162 Operating Systems and Systems Programming Midterm Review"

9/17/12! Ion Stoica CS162 UCB Fall 2012!

Locks and Condition Variables Recap. Introducing Monitors. Hoare Monitors: Semantics. Coke Machine Example. Locks. Condition variables

CS162 Operating Systems and Systems Programming Lecture 9. Tips for Working in a Project Team/ Cooperating Processes and Deadlock

Last Class: CPU Scheduling! Adjusting Priorities in MLFQ!

CS Advanced Operating Systems Structures and Implementation Lecture 8. Synchronization Continued. Goals for Today. Synchronization Scheduling

Synchroniza+on. Today: Implementa+on issues

Today: Synchronization. Recap: Synchronization

Need for synchronization: If threads comprise parts of our software systems, then they must communicate.

Last Class: Deadlocks. Today

Synchronization. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University

Last Class: Synchronization. Review. Semaphores. Today: Semaphores. MLFQ CPU scheduler. What is test & set?

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2002

r ~ c.. Q.) 0\ 7 < - \1") ::J - ::r 3 ::J,... ::J Q.) 0!:t. !:t. ::J ::J (/') C

2 Threads vs. Processes

Lecture #7: Implementing Mutual Exclusion

CS162 Operating Systems and Systems Programming Lecture 9. Tips for Working in a Project Team/ Cooperating Processes and Deadlock

CS11 Java. Fall Lecture 7

Page 1. Goals for Today" Atomic Read-Modify-Write instructions" Examples of Read-Modify-Write "

Page 1. Goals for Today" Atomic Read-Modify-Write instructions" Examples of Read-Modify-Write "

Page 1. Goals for Today. Atomic Read-Modify-Write instructions. Examples of Read-Modify-Write

Page 1. Challenges" Concurrency" CS162 Operating Systems and Systems Programming Lecture 4. Synchronization, Atomic operations, Locks"

Threads Questions Important Questions

MCS-378 Intraterm Exam 1 Serial #:

CS18000: Programming I

Synchronization

5. Synchronization. Operating System Concepts with Java 8th Edition Silberschatz, Galvin and Gagn

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

Threads and Parallelism in Java

Concurrency in Java Prof. Stephen A. Edwards

CSE 153 Design of Operating Systems

CS 31: Introduction to Computer Systems : Threads & Synchronization April 16-18, 2019

Operating Systems CMPSCI 377 Spring Mark Corner University of Massachusetts Amherst

Operating Systems ECE344

CMSC 132: Object-Oriented Programming II. Threads in Java

CS 318 Principles of Operating Systems

MultiThreading 07/01/2013. Session objectives. Introduction. Introduction. Advanced Java Programming Course

Advanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City

Dealing with Issues for Interprocess Communication

The Dining Philosophers Problem CMSC 330: Organization of Programming Languages

Programming in Parallel COMP755

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy

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

Synchronization I. Jo, Heeseung

Condition Variables CS 241. Prof. Brighten Godfrey. March 16, University of Illinois

CMSC 330: Organization of Programming Languages. The Dining Philosophers Problem

Overview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions

Opera&ng Systems ECE344

CS 153 Design of Operating Systems Winter 2016

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017

Synchronization in Concurrent Programming. Amit Gupta

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

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Concurrent Programming using Threads

Computation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007

Multi-threading in Java. Jeff HUANG

Midterm Exam Amy Murphy 19 March 2003

Only one thread can own a specific monitor

CS 571 Operating Systems. Midterm Review. Angelos Stavrou, George Mason University

CSE 332: Locks and Deadlocks. Richard Anderson, Steve Seitz Winter 2014

PROCESS SYNCHRONIZATION

Midterm Exam Solutions and Grading Guidelines March 3, 1999 CS162 Operating Systems

Multiple Inheritance. Computer object can be viewed as

Synchronization II: EventBarrier, Monitor, and a Semaphore. COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Midterm I February 28 th, 2019 CS162: Operating Systems and Systems Programming

Lecture 9: Midterm Review

27/04/2012. We re going to build Multithreading Application. Objectives. MultiThreading. Multithreading Applications. What are Threads?

Problem Set 2. CS347: Operating Systems

Synchronization COMPSCI 386

CMSC 330: Organization of Programming Languages. Threads Classic Concurrency Problems

Process Management And Synchronization

CS 2112 Lecture 20 Synchronization 5 April 2012 Lecturer: Andrew Myers

Thread-Local. Lecture 27: Concurrency 3. Dealing with the Rest. Immutable. Whenever possible, don t share resources

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

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

CMSC421: Principles of Operating Systems

G Programming Languages Spring 2010 Lecture 13. Robert Grimm, New York University

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs

Threading and Synchronization. Fahd Albinali

Java Threads. Written by John Bell for CS 342, Spring 2018

Introduction to Locks. Intrinsic Locks

CMSC 330: Organization of Programming Languages

CSE 120. Fall Lecture 6: Semaphores. Keith Marzullo

Threads and Synchronization. Kevin Webb Swarthmore College February 15, 2018

Synchronization. CISC3595/5595 Fall 2015 Fordham Univ.

Locks. Dongkun Shin, SKKU

Transcription:

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 9: Readers-Writers and Language Support for Synchronization 9.1.2 Constraints 1. Readers can access database when no writers (Condition oktoread) 2. Writers can access database when no readers or writers (Condition oktowrite) 3. Only one thread manipulates state variables at a time. 9.0 Main points: Review definition of monitors and condition variables Illustrate use of monitors and condition variables by solving readers-writers problem Language support can make thread programming easier. Threads are a fundamental OS abstraction, but be careful about how you use them. Summarize concurrency section 9.1.3 Solution Basic structure of solution Reader wait until no writers access database check out wake up waiting writer 9.1 Readers/Writers 9.1.1 Motivation Writer wait until no readers or writers access database check out wake up waiting readers or writer Shared database (for example, bank balances, or airline seats) Two classes of users: Readers never modify database Writers read and modify database Using a single lock on the database would be overly restrictive. Want: many readers at same time only one writer at same time State variables: # of active readers AR = 0 # of active writers AW = 0 # of waiting readers WR = 0 # of waiting writers WW = 0 Condition oktoread = NIL Condition oktowrite = NIL Lock lock = FREE CS 162 Spring 2004 Lecture 9 1/13 CS 162 Spring 2004 Lecture 9 2/13

Code: Reader() { // first check self into system while ((AW + WW) > 0) { // check if safe to read // if any writers, wait WR++; oktoread.wait(&lock); WR--; AR++; Access DB // check self out of system AR--; if (AR == 0 && WW > 0) //if no other readers still // active, wake up writer oktowrite.signal(&lock); Writer() { // symmetrical // check in while ((AW + AR) > 0) { // check if safe to write // if any readers or // writers, wait WW++; oktowrite->wait(&lock); WW--; AW++; Access DB // check out AW--; if (WW > 0) // give priority to other writers oktowrite->signal(&lock); else if (WR > 0) oktoread->broadcast(&lock); Questions: 1. Can readers starve? 2. Why does checkread need a while? CS 162 Spring 2004 Lecture 9 3/13 CS 162 Spring 2004 Lecture 9 4/13

9.2 Comparison between semaphores and monitors Illustrate the differences by considering: can we build monitors out of semaphores? After all, semaphores provide atomic operations and queuing. Does this work? Wait() { semaphore->p(); Signal() { semaphore->v(); Condition variables only work inside of a lock. If you try to use semaphores inside of a lock, you have to watch for deadlock. Does this work? In other words, P + V are commutative result is the same no matter what order they occur. Condition variables are not commutative. That s why they must be in a critical section need to access state variables to do their job. Does this fix the problem? Signal() { if semaphore queue is not empty semaphore->v(); For one, it is not legal to look at contents of semaphore queue. But, there is also a race condition signaler can slip in after lock is released, and before wait. Then waiter never wakes up! Wait(Lock *lock) { lock->release(); semaphore->p(); lock->acquire(); Signal() { semaphore->v(); Program needs to release lock and go to sleep atomically. Is it possible to implement condition variables using semaphores? Yes, but exercise left to the reader! 9.3 Summary of Monitors Monitors represent the logic of the program wait if necessary, signal if change something so waiter might need to wake up. Condition variables have no history, but semaphores do have history. What if thread signals and no one is waiting? No op. What if thread later waits? Thread waits. What if thread V s and no one is waiting? Increment. What if thread later does P? Decrement and continue. CS 162 Spring 2004 Lecture 9 5/13 lock while (need to wait) { wait(); unlock do something so no need to wait lock signal(); unlock CS 162 Spring 2004 Lecture 9 6/13

9.4 Language support for thread synchronization The problem with requiring the programmer to specify both lock acquire and release statements is that he might forget to put a release everywhere it is needed. 9.4.1 Languages like C This is not too bad in a language like C: just make sure you know all the code paths out of a critical section: int Rtn() { lock.acquire(); if (exception) { return errreturncode; return OK; Watch out for setjmp/longjmp! (Might happen in called procedure) 9.4.2 Languages like C++ Languages that support exceptions like C++ are more problematic: void Rtn() { lock.acquire(); DoFoo(); void DoFoo() { if (exception) throw errexception; CS 162 Spring 2004 Lecture 9 7/13 CS 162 Spring 2004 Lecture 9 8/13

Rtn() needs to catch the exception, release the lock, and then re-throw the exception: void Rtn() { lock.acquire(); try { DoFoo(); catch () { // C++ syntax for catching any exception. throw; // C++ syntax for re-throwing an exception. 9.4.3 Java Java has explicit support for threads and thread synchronization. Bank account example: class Account { private int balance; // object constructor public Account (int initialbalance) { balance = initialbalance; Java also has synchronized statements: synchronized (object) { Every Java object has an associated lock. Any Java object can be used to control access to a synchronized block of code. The synchronizing object s lock is acquired on entry and released on exit, even if exit is by means of a thrown exception: synchronized (object) { DoFoo(); void DoFoo() { throw errexception; How to wait in a synchronized method or code block: void wait(long timeout); void wait(long timeout, int nanoseconds); void wait(); How to signal in a synchronized method or code block: void notify(); wakes up the longest waiting waiter void notifyall(); like broadcast,wakes up all waiters public synchronized int getbalance() { return balance; public synchronized void deposit(int amount) { balance += amount; Each Account object has an associated lock, which gets automatically acquired and released on entry and exit from each synchronized method. CS 162 Spring 2004 Lecture 9 9/13 CS 162 Spring 2004 Lecture 9 10/13

Notes: Only one condition variable per lock. Condition variables can wait for a bounded length of time. This is useful for handling exception cases where something has failed. For example: t1 = time.now(); while (!ATMRequest()) { wait(long_time); t2 = time.now(); if (t2 t1 > LONG_TIME) CheckIfMachineBroken(); One reason why all Java Virtual Machines are not equivalent: Different thread scheduling policies. The language specification does not stipulate whether preemptive scheduling is required or what granularity of time slice should be used if preemptive scheduling is provided. 9.5 Concurrency Summary Basic idea in all of computer science is to abstract complexity behind clean interfaces. We ve done that! 9.6 Cautionary Tale: OS/2 Illustrates why an abstraction doesn t always work the way you want it to. Microsoft OS/2 (around 1988): initially, a spectacular failure. Since then, IBM has completely re-written it from scratch. Used threads for everything window systems, communication between programs, etc. Threads are a good idea, right? Thus, system created lots of threads, but few actually running at any one time most waiting around for user to type in a window, or for a network packet to arrive. Might have 100 threads, but just a few at any one time on the ready queue. And each thread needs its own execution stack, say, 9KB, whether it is runnable or waiting. Result: system needs an extra 1 MB of memory, mostly consumed by waiting threads. 1 MB of memory cost $200 in 1988. Physical Hardware Single CPU, interrupts, test&set Programming Abstraction Concurrent sequential execution, infinite # of CPUs, semaphores and monitors Put yourself in the customer s shoes. Did OS/2 run Excel or Word better? OK, it gave you the ability to keep working when you use the printer, but is that worth $200? Every major operating system built since 1985 has provided threads Mach, OS/2, NT (Microsoft), Solaris (SUN), OSF (DEC/Compaq Alphas), and Linux. Why? Because makes it a lot easier to write concurrent programs, from Web servers, to databases, to embedded systems. So does this mean you should all go out and use threads? Moral: threads are cheap, but they re not free. Who are operating systems features for? Operating system developer? End user? Lots of operating systems research has been focused on making it easier for operating systems developers, because it is so complicated to build operating systems. But the trick to selling it is to make it better for the end user. CS 162 Spring 2004 Lecture 9 11/13 CS 162 Spring 2004 Lecture 9 12/13

So, why might making things easier for the OS developer be advantageous to the end user and, more importantly, to the company selling the OS? Things that make an OS slower will fail because the end user will see the slowness. Things that are neutral to the end user, but enable better OS development will succeed because of improved: Time-to-market Cost of maintenance CS 162 Spring 2004 Lecture 9 13/13