Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9

Size: px
Start display at page:

Download "Midterm on next week Tuesday May 4. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9"

Transcription

1 CS 361 Concurrent programming Drexel University Fall 2004 Lecture 9 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce these notes for their own use. Midterm on next week Tuesday May 4 Will cover chapters Will cover chapters 1-3, plus section 4.1 of Hartley book. Also sections ; 3.1, 3.6, 3.7, 4.1; , 5.6 of the Silbershantz Applied Operating Systems textbook. Lecture notes Closed book. Kinds of questions: Describe scenarios and consequences of race conditions Analyze code for properties (mutual exclusion, starvation, deadlock, etc.) Assertions -- what must be true at a certain point in a program? What might be true? What is impossible? Describe/define terms carefully. Describe meaning of code, describe consequences of changing code. Describe the operation of a binary semaphore. page 1 page 2 Lamport s bakery algorithm for mutual exclusion Basic idea: A thread wishing to enter its critical section computes the next ticket number and waits its turn, analogous to customers entering a bakery or deli, drawing a number from the ticket dispenser. page 3 Getting ticket numbers that work concurrently is the crux of the problem. The problem is calculating the ticket number. We can t guarantee that a thread will get a unique number when it tries, due to a race condition in getting the present number. Some computers have a memory get and increment single uninterruptable instruction, but we are assuming only a memory load and store architecture so we don t have a way of doing this without developing a race condition to get the ticket. page 4 Calculating ticket numbers Have the threads compute the next ticket number they will use by using (the maximum of all outstanding ticket numbers) + 1. Two or more threads might compute the same number with this scheme, so a unique constant, numeric identifier associated with each thread is used to break ties. Lamport s bakery algorithm for N threads class Ticket { public volatile int value = 0; class Arbitrator { private static final int NUM_NODES = 2; // for two nodes only // Lamport's bakery ticket algorithm. private Ticket[] ticket = new Ticket[NUM_NODES]; // array of tickets page 5 page 6

2 Lamport s algorithm, con t // Continuation of Arbitrator class // Arbitrator constructor public Arbitrator(int numnodes) { // takes number of contenders as argument. = 2. if (numnodes!= NUM_NODES) { System.err.println("Arbitrator: numnodes=" + numnodes + " which is!= " + NUM_NODES); System.exit(1); ; // initialize array of tickets. for (int i = 0; i < NUM_NODES; i++) ticket[i] = new Ticket(); Other method in Arbitrator class private int other(int i) { return (i + 1) % NUM_NODES; page 7 page 8 Pre-, post- protocols for Lamport algorithm public void wanttoentercs(int i) { // pre-protocol ticket[i].value = 1; ticket[i].value = ticket[other(i)].value + 1; // compute next ticket while (!(ticket[other(i)].value == 0 ticket[i].value < ticket[other(i)].value (ticket[i].value == ticket[other(i)].value // break a tie && i == 0))) /* busy wait */ Thread.currentThread().yield(); public void finishedincs(int i) { ticket[i].value = 0; page 9 // post-protocol page 10 Explanation of ticket condition Another way to state the while condition is: if any of the following is true: If Other thread s ticket is zero, or Your ticket s value is less than other thread s ticket, or Your ticket s value is equal to to the other thread s ticket and you re thread #0. Then proceed into critical section Work out what happens Try to deadlock Try to defeat mutual exclusion Is there starvation in the absence of contention? Try to achieve starvation in the presence of contention Why doesn t the standard problems with race conditions arise? page 11 page 12

3 page 13 No race conditions Because each thread updates a distinct set of variables. So we can t have the read/write/inspect interleaving by multiple threads Lamport s algorithm with more than two threads class Ticket { public volatile int value = 0; class Arbitrator { private int numnodes = 0; // Lamport's bakery ticket algorithm. private Ticket[] ticket = null; public Arbitrator(int numnodes) { this.numnodes = numnodes; ticket = new Ticket[numNodes]; for (int i = 0; i < numnodes; i++) ticket[i] = new Ticket(); private int maxx(ticket[] ticket) { // find maximum of all tickets int mx = ticket[0].value; for (int i = 1; i < ticket.length; i++) if (ticket[i].value > mx) mx = ticket[i].value; return mx; page 14 Lamport s algorithm with more than two threads public void wanttoentercs(int i) { // pre-protocol ticket[i].value = 1; ticket[i].value = 1 + maxx(ticket); // compute next ticket for (int j = 0; j < numnodes; j++) if (j!= i) while (!(ticket[j].value == 0 ticket[i].value < ticket[j].value // break a tie (ticket[i].value == ticket[j].value && i < j))) // busy wait Thread.currentThread().yield(); public void finishedincs(int i) { ticket[i].value = 0; // post-protocol Notes on the condition So now we proceed into the critical section if, for all nodes j!= i, at least one of the following is true: Thread j s ticket is zero, or Thread j s ticket value is higher than that of ticket i, or Thread j s ticket value is equal to that of thread i s ticket, but i has the smallest thread number of all those threads (tie breaker) page 15 page 16 page 17 Nice properties of Lamport s algorithm Lamport s bakery algorithm has all good properties it enforces mutual exclusion, it does not deadlock, it does not livelock, it prevents starvation in the absence of contention, and it prevents starvation in the presence of contention. How to enforce mutual exclusion via hardware Method #1: turn off interrupts works on uniprocessor machines. Also need to hardware-lock the memory bus. Turning off interrupts means that time-slicing can t happen, so a thread running will continue to run until it yields Don t waste cycles busy-waiting. Some OS s running in privileged (kernel) mode allow this But makes the machine unresponsive to anything else while thread is in critical section. Doesn t work well with multiprocessors. page 18

4 Method #2: test and set instruction TS(R, addr, value) : Retrieves the value of addr into R, and then stores the specified value into addr. An atomic, uninterruptable assembly language instruction found on many computers. From this we can build a software procedure useful for mutual exclusion boolean testandset(boolean flag) { Register R; TS(R, flag, true); // get current value of flag // and set that flag to true, in one // uninterruptable operation. return R; page 19 page 20 Using testandset to implement mutual exclusion boolean lockflag = false; wanttoentercs(int I) { while testandset(lockflag) /* busy wait */ ; finished InCS(int I) { lockflag = false; Works for any number of threads Does not deadlock Does not suffer from starvation in the absence of contention. There may be starvation in the presence of contention because some thread could be locked out. Solutions that use blocking Busy waiting burns CPU cycles during the wait, particularly with a multiprocessor situation. Can we use features such as Java s wait and notify to avoid needless usage of cycles? Ideal methods delay() and wakeup() delay() would remove its thread from runnable and placed it at the end of a queue of delayed threads. Its state is changed from running to blocked. wakeup() (by a running thread, not the delayed one, obviously) moves a thread at the head of the delay queue back to the ready queue and its state is changed from blocked to runnable. If the delay queue is empty, wakeup has no effect. We avoid busy waiting for threads in the delay queue. page 21 page 22 Does this work? public void wanttoentercs(int I) { desirecs[i].value = true; last = I; while (desirecs[other(i)].value && last == I) delay(); public void finishedincs(int I){ desirecs[i].value = false; wakeup(); A problem with this approach: missed signal. If there s a context switch by a thread executing wanttoentercs between the time that it does the while test and the time it does the delay, then if the other thread does the wakeup before the the thread in the preprotocol does the delay, it could miss the wakeup and then hang forever. page 23 page 24

5 Bounded buffer code, revisited Producer consumer code // Class 3.19 (p.84) public void deposit(double value) { public double fetch() { if (buffer[putin].occupied) { double value; Thread producer = Thread.currentThread(); if (!buffer[takeout].occupied) { buffer[putin].thread = producer; buffer[takeout].thread = consumer; producer.suspend(); consumer.suspend(); // bad context switch here? // bad context switch? buffer[takeout].thread=null; buffer[putin].thread = null; ; value = buffer[takeout].value; buffer[putin].value = value; buffer[takeout].occupied = false; buffer[putin].occupied = true; Thread producer = buffer[takeout].thread; Thread consumer = buffer[putin].thread; if (producer!= null) putin = (putin + 1) & numslots; producer.resume();// a producer is waiting if (consumer!=null) consumer.resume(); Return value; // a consumer is waiting. page 25 page 26 What goes wrong with this? This has the same problem as the original pseudo code: a missed wakeup because the resume occurs before the suspend. A busy waiting solution to the bounded buffer problem class BufferItem { public volatile double value = 0; // multiple threads access public volatile boolean occupied = false; // so make these `volatile' page 27 page 28 Bounded buffer class class BoundedBuffer { // designed for a single producer thread and // a single consumer thread private int numslots = 0; private BufferItem[] buffer = null; private int putin = 0, takeout = 0; // private int count = 0; public BoundedBuffer(int numslots) { if (numslots <= 0) throw new IllegalArgumentException("numSlots<=0"); this.numslots = numslots; buffer = new BufferItem[numSlots]; for (int i = 0; i < numslots; i++) buffer[i] = new BufferItem(); Busy waiting bounded buffer producer public void deposit(double value) { while (buffer[putin].occupied) // busy wait Thread.currentThread().yield(); buffer[putin].value = value; // A buffer[putin].occupied = true; // B putin = (putin + 1) % numslots; // count++; // race condition!!! page 29 page 30

6 Busy waiting bounded buffer consumer public double fetch() { double value; while (!buffer[takeout].occupied) // busy wait Thread.currentThread().yield(); value = buffer[takeout].value; // C buffer[takeout].occupied = false; // D takeout = (takeout + 1) % numslots; // count--; // race condition!!! return value; What could go wrong here? It uses value and occupied which must be declared volatile if the consumer is to see things in the same order as the producer is setting them (and vice versa) If the consumer thread has a higher priority than the producer then the consumer thread could busy-wait forever and prevent the producer from ever getting a time slice in which to put something into the buffer. This is a form of starvation even though there is no critical section. This is always a danger on a system that doesn t have time-slicing. page 31 page 32 page 33 Semaphores A counting semaphore is an abstract data type with two atomic (uninterruptable) operations, P and V. The data field known as the value of the semaphore is an integer which is supposed to take on non-negative values (0, 1, 2, ). When created the value of the semaphore is initialized by the constructor, e.g. Semaphore S = new Semaphore(1); s.p() or P(s) is known as down (or dutch for passeren, to pass) s.v() or V(s) is known as up (or vrygeven, to release) page 34 Semaphore semantics The P operation decrements S in an atomic (noninterruptable) action) if it is > 0. Then the thread doing the P operation proceeds. Otherwise, if the value of the semaphore is already 0, the thread doing the P operation waits. If a thread invokes the V operation, then if no thread is waiting (from doing a P) then the value of the semaphore is incremented and the thread doing the V operation proceeds. If a thread invokes the V operation, then if another thread is waiting (from doing a P operation with the semaphore) then one of the waiting threads is released, and the thread doing the V operation is proceeds. The value of the semaphore is not incremented in this case. Semaphore notes Do some scenarios. Remember P and V are atomic (uninterruptable) operations. Can have several semaphores S1, S2, S3, etc. in a program. Doing a S1.P() or S1.V() doesn t affect operations with S2, S3, etc. Another notation for describing P and V, with s holding the value of the semaphore. P: < await (s>0); s = s-1;> V: <s = s+1;>. page 35 page 36

7 Binary semaphores A binary semaphore is limited to the values 0 and 1. A V operation applied to a semaphore whose value is already 1 has no effect. Binary semaphores are also called mutex locks. With some implementations of binary semaphores, sometimes P is named lock and V is named unlock. Locks Sometimes the concept of a lock is refined to include the idea that only the holder of a lock is allowed to release it. This makes sense when the lock is to give the holder exclusive access to a resource. However, sometimes a binary semaphore is used to block a thread until some event caused by another thread has occurred. For that reason, binary semaphores don t have any restrictions on who does the down and who does the up. page 37 page 38 Back to general binary semaphores Binary semaphores are used for mutual exclusion synchronization (enforcing mutual exclusion into critical sections) and condition synchronization (blocking threads until some condition becomes true or some event occurs, as with producer/consumer). How to do mutual exclusion with binary semaphores Shared binary semaphore mutex with initial value 1 mutex.p() // pre protocol Critical section; mutex.v() // post protocol page 39 page 40 Do some scenarios. Semaphore S = new Semaphore(1);// initialize to 1 S.P(); (critical section) S.V(); 1. Thread A does S.P(); Decrements semaphore to 0, returns from call to P, proceeds into critical section. Do some scenarios. 2. Thread B does S.P(); Blocks. 3. Thread C does S.P(); Blocks. 4. Thread A finishes CS, do S.V(); Instead of incrementing value of semaphore, it unblocks a thread, say B. A has finished CS. 5. What happens if thread A does an S.P() at this point? (blocks) 6. Thread B finished CS, does S.V();. Unblocks a thread, say A. 7. A finished, does S.V(); unblocks C. 8. C finishes CS, does S.V();, semaphore is set to 1. page 41 page 42

8 Binary semaphores also handle the producer/consumer problem In general the way to do condition synchronization with binary semaphores is: In one thread: if (condition) P(S); // blocks For example, for consumer thread, if buffer is empty, then do a P(S) which will block if semaphore is initially zero. In producer thread: as soon as product is placed in buffer, V(S); // giving permission to the other thread to unblock. No missed signals; we can do P(S) followed by V(S) or vice versa. page 43 page 44 Producer/consumer code with binary semaphores. int N, count = 0; BinarySemaphore S = new BinaryhSemaphore(0), mutex = new BinarySemaphore (1); public void producer() { while (true) { produceitem(); if (count == N) P(S); // block if buffer full enteritem(); P(mutex); count ++; V(mutex); // critical section // protected for mutual exclusion if (count == 1) V(S); Consumer code with binary semaphores public void consumer() { while (true) { if (count == 0) P(S); // delay if buffer empty removeitem(); P(mutex); count --; V(mutex); // critical section if (count == N -1) V(s); // release consumer if it s waiting. consumeitem(); Questions about this code Go through a scenario of what happens when the producer produces into an unfull buffer, and into a full buffer. Why are two and not only one semaphores needed? page 45 page 46

Memory system behavior: volatile variables. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 6. Volatile variables and concurrency

Memory system behavior: volatile variables. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 6. Volatile variables and concurrency CS 361 Concurrent programming Dreel University Fall 2004 Lecture 6 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

Pre- and post- CS protocols. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 7. Other requirements for a mutual exclusion algorithm

Pre- and post- CS protocols. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 7. Other requirements for a mutual exclusion algorithm CS 361 Concurrent programming Drexel University Fall 2004 Lecture 7 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

CS 361 Concurrent programming Drexel University Fall 2004 Lecture 8. Proof by contradiction. Proof of correctness. Proof of mutual exclusion property

CS 361 Concurrent programming Drexel University Fall 2004 Lecture 8. Proof by contradiction. Proof of correctness. Proof of mutual exclusion property CS 361 Concurrent programming Drexel University Fall 2004 Lecture 8 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

Concept of a process

Concept of a process Concept of a process In the context of this course a process is a program whose execution is in progress States of a process: running, ready, blocked Submit Ready Running Completion Blocked Concurrent

More information

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

CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14. The dining philosophers problem CS 361 Concurrent programming Drexel University Spring 2000 Lecture 14 Bruce Char. All rights reserved by the author. Permission is given to students enrolled in CS361 Spring 2000 to reproduce these notes

More information

CSE Traditional Operating Systems deal with typical system software designed to be:

CSE Traditional Operating Systems deal with typical system software designed to be: CSE 6431 Traditional Operating Systems deal with typical system software designed to be: general purpose running on single processor machines Advanced Operating Systems are designed for either a special

More information

Models of concurrency & synchronization algorithms

Models of concurrency & synchronization algorithms Models of concurrency & synchronization algorithms Lecture 3 of TDA383/DIT390 (Concurrent Programming) Carlo A. Furia Chalmers University of Technology University of Gothenburg SP3 2016/2017 Today s menu

More information

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor.

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor. Synchronization 1 Concurrency On multiprocessors, several threads can execute simultaneously, one on each processor. On uniprocessors, only one thread executes at a time. However, because of preemption

More information

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

Operating Systems. Lecture 4 - Concurrency and Synchronization. Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Operating Systems Lecture 4 - Concurrency and Synchronization Adrien Krähenbühl Master of Computer Science PUF - Hồ Chí Minh 2016/2017 Mutual exclusion Hardware solutions Semaphores IPC: Message passing

More information

Synchronization. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han

Synchronization. CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han Synchronization CSCI 3753 Operating Systems Spring 2005 Prof. Rick Han Announcements HW #3 is coming, due Friday Feb. 25, a week+ from now PA #2 is coming, assigned about next Tuesday Midterm is tentatively

More information

Dealing with Issues for Interprocess Communication

Dealing with Issues for Interprocess Communication Dealing with Issues for Interprocess Communication Ref Section 2.3 Tanenbaum 7.1 Overview Processes frequently need to communicate with other processes. In a shell pipe the o/p of one process is passed

More information

Dr. D. M. Akbar Hussain DE5 Department of Electronic Systems

Dr. D. M. Akbar Hussain DE5 Department of Electronic Systems Concurrency 1 Concurrency Execution of multiple processes. Multi-programming: Management of multiple processes within a uni- processor system, every system has this support, whether big, small or complex.

More information

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

Operating Systems. Designed and Presented by Dr. Ayman Elshenawy Elsefy Operating Systems Designed and Presented by Dr. Ayman Elshenawy Elsefy Dept. of Systems & Computer Eng.. AL-AZHAR University Website : eaymanelshenawy.wordpress.com Email : eaymanelshenawy@yahoo.com Reference

More information

Chapter 5 Asynchronous Concurrent Execution

Chapter 5 Asynchronous Concurrent Execution Chapter 5 Asynchronous Concurrent Execution Outline 5.1 Introduction 5.2 Mutual Exclusion 5.2.1 Java Multithreading Case Study 5.2.2 Critical Sections 5.2.3 Mutual Exclusion Primitives 5.3 Implementing

More information

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

Chapter 6: Process Synchronization. Operating System Concepts 8 th Edition, Chapter 6: Process Synchronization, Silberschatz, Galvin and Gagne 2009 Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores

More information

Semaphores. May 10, Mutual exclusion with shared variables is difficult (e.g. Dekker s solution).

Semaphores. May 10, Mutual exclusion with shared variables is difficult (e.g. Dekker s solution). Semaphores May 10, 2000 1 Introduction Mutual exclusion with shared variables is difficult (e.g. Dekker s solution). Generalising to an arbitrary number of processes is also nontrivial (e.g. Lamport s

More information

Synchronization for Concurrent Tasks

Synchronization for Concurrent Tasks Synchronization for Concurrent Tasks Minsoo Ryu Department of Computer Science and Engineering 2 1 Race Condition and Critical Section Page X 2 Algorithmic Approaches Page X 3 Hardware Support Page X 4

More information

Process Coordination

Process Coordination Process Coordination Why is it needed? Processes may need to share data More than one process reading/writing the same data (a shared file, a database record, ) Output of one process being used by another

More information

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

CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring Lecture 8: Semaphores, Monitors, & Condition Variables CS 162 Operating Systems and Systems Programming Professor: Anthony D. Joseph Spring 2004 Lecture 8: Semaphores, Monitors, & Condition Variables 8.0 Main Points: Definition of semaphores Example of use

More information

CS-537: Midterm Exam (Spring 2001)

CS-537: Midterm Exam (Spring 2001) CS-537: Midterm Exam (Spring 2001) Please Read All Questions Carefully! There are seven (7) total numbered pages Name: 1 Grading Page Points Total Possible Part I: Short Answers (12 5) 60 Part II: Long

More information

Introduction to OS Synchronization MOS 2.3

Introduction to OS Synchronization MOS 2.3 Introduction to OS Synchronization MOS 2.3 Mahmoud El-Gayyar elgayyar@ci.suez.edu.eg Mahmoud El-Gayyar / Introduction to OS 1 Challenge How can we help processes synchronize with each other? E.g., how

More information

Interprocess Communication By: Kaushik Vaghani

Interprocess Communication By: Kaushik Vaghani Interprocess Communication By: Kaushik Vaghani Background Race Condition: A situation where several processes access and manipulate the same data concurrently and the outcome of execution depends on the

More information

CS420: Operating Systems. Process Synchronization

CS420: Operating Systems. Process Synchronization Process Synchronization James Moscola Department of Engineering & Computer Science York College of Pennsylvania Based on Operating System Concepts, 9th Edition by Silberschatz, Galvin, Gagne Background

More information

Concurrency. Chapter 5

Concurrency. Chapter 5 Concurrency 1 Chapter 5 2 Concurrency Is a fundamental concept in operating system design Processes execute interleaved in time on a single processor Creates the illusion of simultaneous execution Benefits

More information

IT 540 Operating Systems ECE519 Advanced Operating Systems

IT 540 Operating Systems ECE519 Advanced Operating Systems IT 540 Operating Systems ECE519 Advanced Operating Systems Prof. Dr. Hasan Hüseyin BALIK (5 th Week) (Advanced) Operating Systems 5. Concurrency: Mutual Exclusion and Synchronization 5. Outline Principles

More information

G52CON: Concepts of Concurrency

G52CON: Concepts of Concurrency G52CON: Concepts of Concurrency Lecture 11: Semaphores I" Brian Logan School of Computer Science bsl@cs.nott.ac.uk Outline of this lecture" problems with Peterson s algorithm semaphores implementing semaphores

More information

ENGR 3950U / CSCI 3020U UOIT, Fall 2012 Quiz on Process Synchronization SOLUTIONS

ENGR 3950U / CSCI 3020U UOIT, Fall 2012 Quiz on Process Synchronization SOLUTIONS Name: Student Number: SOLUTIONS ENGR 3950U / CSCI 3020U (Operating Systems) Quiz on Process Synchronization November 13, 2012, Duration: 40 Minutes (10 questions and 8 pages, 45 Marks) Instructor: Dr.

More information

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor.

Concurrency. On multiprocessors, several threads can execute simultaneously, one on each processor. Synchronization 1 Concurrency On multiprocessors, several threads can execute simultaneously, one on each processor. On uniprocessors, only one thread executes at a time. However, because of preemption

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Objectives Introduce Concept of Critical-Section Problem Hardware and Software Solutions of Critical-Section Problem Concept of Atomic Transaction Operating Systems CS

More information

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Learning Outcomes Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

More information

CS370 Operating Systems

CS370 Operating Systems CS370 Operating Systems Colorado State University Yashwant K Malaiya Fall 2017 Lecture 11 Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ Multilevel Feedback Queue: Q0, Q1,

More information

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 Goals for Today" CS162 Operating Systems and Systems Programming Lecture 5 Semaphores, Conditional Variables" Atomic instruction sequence Continue with Synchronization Abstractions Semaphores, Monitors

More information

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java

Quiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce

More information

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

Chapter 6: Synchronization. Operating System Concepts 8 th Edition, Chapter 6: Synchronization, Silberschatz, Galvin and Gagne 2009 Outline Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization

More information

Chapter 5 Concurrency: Mutual Exclusion and Synchronization

Chapter 5 Concurrency: Mutual Exclusion and Synchronization Operating Systems: Internals and Design Principles Chapter 5 Concurrency: Mutual Exclusion and Synchronization Seventh Edition By William Stallings Designing correct routines for controlling concurrent

More information

Programming in Parallel COMP755

Programming in Parallel COMP755 Programming in Parallel COMP755 All games have morals; and the game of Snakes and Ladders captures, as no other activity can hope to do, the eternal truth that for every ladder you hope to climb, a snake

More information

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition

Chapter 5: Process Synchronization. Operating System Concepts Essentials 2 nd Edition Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013 Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks

More information

Chapter 6: Process Synchronization

Chapter 6: Process Synchronization Chapter 6: Process Synchronization Chapter 6: Synchronization 6.1 Background 6.2 The Critical-Section Problem 6.3 Peterson s Solution 6.4 Synchronization Hardware 6.5 Mutex Locks 6.6 Semaphores 6.7 Classic

More information

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013 Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks

More information

Concurrency and Synchronisation

Concurrency and Synchronisation Concurrency and Synchronisation 1 Sections 2.3 & 2.4 Textbook 2 Making Single-Threaded Code Multithreaded Conflicts between threads over the use of a global variable 3 Inter- Thread and Process Communication

More information

2.c Concurrency Mutual exclusion & synchronization mutexes. Unbounded buffer, 1 producer, N consumers

2.c Concurrency Mutual exclusion & synchronization mutexes. Unbounded buffer, 1 producer, N consumers Mutual exclusion & synchronization mutexes Unbounded buffer, 1 producer, N consumers out shared by all consumers mutex among consumers producer not concerned: can still add items to buffer at any time

More information

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

CS 333 Introduction to Operating Systems. Class 4 Concurrent Programming and Synchronization Primitives CS 333 Introduction to Operating Systems Class 4 Concurrent Programming and Synchronization Primitives Jonathan Walpole Computer Science Portland State University 1 Concurrent programming Assumptions:

More information

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

Learning Outcomes. Concurrency and Synchronisation. Textbook. Concurrency Example. Inter- Thread and Process Communication. Sections & 2. Learning Outcomes Concurrency and Synchronisation Understand concurrency is an issue in operating systems and multithreaded applications Know the concept of a critical region. Understand how mutual exclusion

More information

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018

SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T A N D S P R I N G 2018 SYNCHRONIZATION M O D E R N O P E R A T I N G S Y S T E M S R E A D 2. 3 E X C E P T 2. 3. 8 A N D 2. 3. 1 0 S P R I N G 2018 INTER-PROCESS COMMUNICATION 1. How a process pass information to another process

More information

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

Chapter 6: Synchronization. Chapter 6: Synchronization. 6.1 Background. Part Three - Process Coordination. Consumer. Producer. 6. Part Three - Process Coordination Chapter 6: Synchronization 6.1 Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure

More information

Concurrent Processes Rab Nawaz Jadoon

Concurrent Processes Rab Nawaz Jadoon Concurrent Processes Rab Nawaz Jadoon DCS COMSATS Institute of Information Technology Assistant Professor COMSATS Lahore Pakistan Operating System Concepts Concurrent Processes If more than one threads

More information

Locks. Dongkun Shin, SKKU

Locks. Dongkun Shin, SKKU Locks 1 Locks: The Basic Idea To implement a critical section A lock variable must be declared A lock variable holds the state of the lock Available (unlocked, free) Acquired (locked, held) Exactly one

More information

IV. Process Synchronisation

IV. Process Synchronisation IV. Process Synchronisation Operating Systems Stefan Klinger Database & Information Systems Group University of Konstanz Summer Term 2009 Background Multiprogramming Multiple processes are executed asynchronously.

More information

Synchronization Principles

Synchronization Principles Synchronization Principles Gordon College Stephen Brinton The Problem with Concurrency Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms

More information

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 Goals for Today" CS162 Operating Systems and Systems Programming Lecture 5 Semaphores, Conditional Variables" Atomic instruction sequence Continue with Synchronization Abstractions Semaphores, Monitors

More information

2 Threads vs. Processes

2 Threads vs. Processes 9 2 Threads vs. Processes A process includes an address space (defining all the code and data pages) a resource container (OS resource and accounting information) a thread of control, which defines where

More information

Lesson 6: Process Synchronization

Lesson 6: Process Synchronization Lesson 6: Process Synchronization Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks Semaphores Classic Problems of Synchronization

More information

PROCESS SYNCHRONIZATION

PROCESS SYNCHRONIZATION PROCESS SYNCHRONIZATION Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores Classic Problems of Synchronization Monitors Synchronization

More information

Dept. of CSE, York Univ. 1

Dept. of CSE, York Univ. 1 EECS 3221.3 Operating System Fundamentals No.5 Process Synchronization(1) Prof. Hui Jiang Dept of Electrical Engineering and Computer Science, York University Background: cooperating processes with shared

More information

Process Synchronization

Process Synchronization Process Synchronization Chapter 6 2015 Prof. Amr El-Kadi Background Concurrent access to shared data may result in data inconsistency Maintaining data consistency requires mechanisms to ensure the orderly

More information

Synchronization I. Jo, Heeseung

Synchronization I. Jo, Heeseung Synchronization I Jo, Heeseung Today's Topics Synchronization problem Locks 2 Synchronization Threads cooperate in multithreaded programs To share resources, access shared data structures Also, to coordinate

More information

Background. The Critical-Section Problem Synchronisation Hardware Inefficient Spinning Semaphores Semaphore Examples Scheduling.

Background. The Critical-Section Problem Synchronisation Hardware Inefficient Spinning Semaphores Semaphore Examples Scheduling. Background The Critical-Section Problem Background Race Conditions Solution Criteria to Critical-Section Problem Peterson s (Software) Solution Concurrent access to shared data may result in data inconsistency

More information

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 Goals for Today CS162 Operating Systems and Systems Programming Lecture 5 Atomic instruction sequence Continue with Synchronization Abstractions Semaphores, Monitors and condition variables Semaphores,

More information

Process Management And Synchronization

Process Management And Synchronization Process Management And Synchronization In a single processor multiprogramming system the processor switches between the various jobs until to finish the execution of all jobs. These jobs will share the

More information

CS 153 Design of Operating Systems Winter 2016

CS 153 Design of Operating Systems Winter 2016 CS 153 Design of Operating Systems Winter 2016 Lecture 7: Synchronization Administrivia Homework 1 Due today by the end of day Hopefully you have started on project 1 by now? Kernel-level threads (preemptable

More information

Chapter 5 Concurrency: Mutual Exclusion. and. Synchronization. Operating Systems: Internals. and. Design Principles

Chapter 5 Concurrency: Mutual Exclusion. and. Synchronization. Operating Systems: Internals. and. Design Principles Operating Systems: Internals and Design Principles Chapter 5 Concurrency: Mutual Exclusion and Synchronization Seventh Edition By William Stallings Designing correct routines for controlling concurrent

More information

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

Synchronization. CS 416: Operating Systems Design, Spring 2011 Department of Computer Science Rutgers University Synchronization Design, Spring 2011 Department of Computer Science Synchronization Basic problem: Threads are concurrently accessing shared variables The access should be controlled for predictable result.

More information

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

Operating Systems. Operating Systems Summer 2017 Sina Meraji U of T Operating Systems Operating Systems Summer 2017 Sina Meraji U of T More Special Instructions Swap (or Exchange) instruction Operates on two words atomically Can also be used to solve critical section problem

More information

CHAPTER 6: PROCESS SYNCHRONIZATION

CHAPTER 6: PROCESS SYNCHRONIZATION CHAPTER 6: PROCESS SYNCHRONIZATION The slides do not contain all the information and cannot be treated as a study material for Operating System. Please refer the text book for exams. TOPICS Background

More information

ECE469 - Operating Systems Engineering Exam # March 25

ECE469 - Operating Systems Engineering Exam # March 25 ECE469 - Operating Systems Engineering Exam #1 2004 March 25 A computer lets you make more mistakes faster than any invention in human history with the possible exceptions of handguns and tequila. Mitch

More information

Process Synchronization. Mehdi Kargahi School of ECE University of Tehran Spring 2008

Process Synchronization. Mehdi Kargahi School of ECE University of Tehran Spring 2008 Process Synchronization Mehdi Kargahi School of ECE University of Tehran Spring 2008 Producer-Consumer (Bounded Buffer) Producer Consumer Race Condition Producer Consumer Critical Sections Structure of

More information

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently. UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING 1. What are Threads? A thread is a single path of execution of code in a program. A Multithreaded program contains two or more parts that can run concurrently.

More information

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

CS 31: Introduction to Computer Systems : Threads & Synchronization April 16-18, 2019 CS 31: Introduction to Computer Systems 22-23: Threads & Synchronization April 16-18, 2019 Making Programs Run Faster We all like how fast computers are In the old days (1980 s - 2005): Algorithm too slow?

More information

CS3733: Operating Systems

CS3733: Operating Systems Outline CS3733: Operating Systems Topics: Synchronization, Critical Sections and Semaphores (SGG Chapter 6) Instructor: Dr. Tongping Liu 1 Memory Model of Multithreaded Programs Synchronization for coordinated

More information

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition

Module 6: Process Synchronization. Operating System Concepts with Java 8 th Edition Module 6: Process Synchronization 6.1 Silberschatz, Galvin and Gagne 2009 Module 6: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Semaphores

More information

10/17/2011. Cooperating Processes. Synchronization 1. Example: Producer Consumer (3) Example

10/17/2011. Cooperating Processes. Synchronization 1. Example: Producer Consumer (3) Example Cooperating Processes Synchronization 1 Chapter 6.1 4 processes share something (devices such as terminal, keyboard, mouse, etc., or data structures) and can affect each other non deterministic Not exactly

More information

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition

Chapter 5: Process Synchronization. Operating System Concepts 9 th Edition Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013 Chapter 5: Process Synchronization Background The Critical-Section Problem Peterson s Solution Synchronization Hardware Mutex Locks

More information

Process Synchronization

Process Synchronization CSC 4103 - Operating Systems Spring 2007 Lecture - VI Process Synchronization Tevfik Koşar Louisiana State University February 6 th, 2007 1 Roadmap Process Synchronization The Critical-Section Problem

More information

Implementing Mutual Exclusion. Sarah Diesburg Operating Systems CS 3430

Implementing Mutual Exclusion. Sarah Diesburg Operating Systems CS 3430 Implementing Mutual Exclusion Sarah Diesburg Operating Systems CS 3430 From the Previous Lecture The too much milk example shows that writing concurrent programs directly with load and store instructions

More information

UNIX Input/Output Buffering

UNIX Input/Output Buffering UNIX Input/Output Buffering When a C/C++ program begins execution, the operating system environment is responsible for opening three files and providing file pointers to them: stdout standard output stderr

More information

Process Synchronization

Process Synchronization Process Synchronization Concurrent access to shared data may result in data inconsistency Multiple threads in a single process Maintaining data consistency requires mechanisms to ensure the orderly execution

More information

Introduction to Operating Systems

Introduction to Operating Systems Introduction to Operating Systems Lecture 4: Process Synchronization MING GAO SE@ecnu (for course related communications) mgao@sei.ecnu.edu.cn Mar. 18, 2015 Outline 1 The synchronization problem 2 A roadmap

More information

Lecture 6. Process Synchronization

Lecture 6. Process Synchronization Lecture 6 Process Synchronization 1 Lecture Contents 1. Principles of Concurrency 2. Hardware Support 3. Semaphores 4. Monitors 5. Readers/Writers Problem 2 1. Principles of Concurrency OS design issue

More information

CS Operating Systems

CS Operating Systems CS 4500 - Operating Systems Module 4: The Producer-Consumer Problem and Solution Methods Stanley Wileman Department of Computer Science University of Nebraska at Omaha Omaha, NE 68182-0500, USA June 3,

More information

CS Operating Systems

CS Operating Systems CS 4500 - Operating Systems Module 4: The Producer-Consumer Problem and Solution Methods Stanley Wileman Department of Computer Science University of Nebraska at Omaha Omaha, NE 68182-0500, USA June 3,

More information

1 Process Coordination

1 Process Coordination COMP 730 (242) Class Notes Section 5: Process Coordination 1 Process Coordination Process coordination consists of synchronization and mutual exclusion, which were discussed earlier. We will now study

More information

Concurrency: a crash course

Concurrency: a crash course Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Concurrency: a crash course Concurrent computing Applications designed as a collection of computational units that may execute

More information

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems

Synchronization. CS 475, Spring 2018 Concurrent & Distributed Systems Synchronization CS 475, Spring 2018 Concurrent & Distributed Systems Review: Threads: Memory View code heap data files code heap data files stack stack stack stack m1 m1 a1 b1 m2 m2 a2 b2 m3 m3 a3 m4 m4

More information

COMP 300E Operating Systems Fall Semester 2011 Midterm Examination SAMPLE. Name: Student ID:

COMP 300E Operating Systems Fall Semester 2011 Midterm Examination SAMPLE. Name: Student ID: COMP 300E Operating Systems Fall Semester 2011 Midterm Examination SAMPLE Time/Date: 5:30 6:30 pm Oct 19, 2011 (Wed) Name: Student ID: 1. Short Q&A 1.1 Explain the convoy effect with FCFS scheduling algorithm.

More information

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

Need for synchronization: If threads comprise parts of our software systems, then they must communicate. Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.

More information

Synchronization. Before We Begin. Synchronization. Credit/Debit Problem: Race Condition. CSE 120: Principles of Operating Systems.

Synchronization. Before We Begin. Synchronization. Credit/Debit Problem: Race Condition. CSE 120: Principles of Operating Systems. CSE 120: Principles of Operating Systems Lecture 4 Synchronization January 23, 2006 Prof. Joe Pasquale Department of Computer Science and Engineering University of California, San Diego Before We Begin

More information

Synchronization: Semaphores

Synchronization: Semaphores Illinois Institute of Technology Lecture 26 4/25 solved Synchronization: Semaphores CS 536: Science of Programming, Spring 2018 A. Why Avoiding interference, while good, isn t the same as coordinating

More information

Process Synchronisation (contd.) Operating Systems. Autumn CS4023

Process Synchronisation (contd.) Operating Systems. Autumn CS4023 Operating Systems Autumn 2017-2018 Outline Process Synchronisation (contd.) 1 Process Synchronisation (contd.) Synchronization Hardware 6.4 (SGG) Many systems provide hardware support for critical section

More information

Do not start the test until instructed to do so!

Do not start the test until instructed to do so! CS 3204 Operating Systems Midterm (Abrams) Spring 2004 VIRG INIA POLYTECHNIC INSTITUTE AND STATE U T PRO SI M UNI VERSI TY Instructions: Do not start the test until instructed to do so! Print your name

More information

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

Week 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand

More information

Concurrency: Mutual Exclusion and

Concurrency: Mutual Exclusion and Concurrency: Mutual Exclusion and Synchronization 1 Needs of Processes Allocation of processor time Allocation and sharing resources Communication among processes Synchronization of multiple processes

More information

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions

Chapter 2 Processes and Threads. Interprocess Communication Race Conditions Chapter 2 Processes and Threads [ ] 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling 85 Interprocess Communication Race Conditions Two processes want to access shared memory at

More information

Chapter 8. Basic Synchronization Principles

Chapter 8. Basic Synchronization Principles Chapter 8 Basic Synchronization Principles Need for Synchronization Multiprogramming Multiple concurrent, independent processes Those processes might want to coordinate activities Proc A { while (true)

More information

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack

Recap: Thread. What is it? What does it need (thread private)? What for? How to implement? Independent flow of control. Stack What is it? Recap: Thread Independent flow of control What does it need (thread private)? Stack What for? Lightweight programming construct for concurrent activities How to implement? Kernel thread vs.

More information

Lecture 8: September 30

Lecture 8: September 30 CMPSCI 377 Operating Systems Fall 2013 Lecture 8: September 30 Lecturer: Prashant Shenoy Scribe: Armand Halbert 8.1 Semaphores A semaphore is a more generalized form of a lock that can be used to regulate

More information

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

CSE 451: Operating Systems Winter Lecture 7 Synchronization. Steve Gribble. Synchronization. Threads cooperate in multithreaded programs CSE 451: Operating Systems Winter 2005 Lecture 7 Synchronization Steve Gribble Synchronization Threads cooperate in multithreaded programs to share resources, access shared data structures e.g., threads

More information

Mutual Exclusion and Synchronization

Mutual Exclusion and Synchronization Mutual Exclusion and Synchronization Concurrency Defined Single processor multiprogramming system Interleaving of processes Multiprocessor systems Processes run in parallel on different processors Interleaving

More information

Last class: Today: CPU Scheduling. Start synchronization

Last class: Today: CPU Scheduling. Start synchronization Last class: CPU Scheduling Today: Start synchronization Synchronization Processes (threads) share resources. How do processes share resources? How do threads share resources? It is important to coordinate

More information

Concurrency: Locks. Announcements

Concurrency: Locks. Announcements CS 537 Introduction to Operating Systems UNIVERSITY of WISCONSIN-MADISON Computer Sciences Department Concurrency: Locks Andrea C. Arpaci-Dusseau Remzi H. Arpaci-Dusseau Questions answered in this lecture:

More information

Chapters 5 and 6 Concurrency

Chapters 5 and 6 Concurrency Operating Systems: Internals and Design Principles, 6/E William Stallings Chapters 5 and 6 Concurrency Patricia Roy Manatee Community College, Venice, FL 2008, Prentice Hall Concurrency When several processes/threads

More information