# Operating Systems ECE344

Save this PDF as:

Size: px
Start display at page:

## Transcription

1 Operating Systems ECE344 Ding Yuan Announcement & Reminder Lab 0 mark posted on Piazza Great job! One problem: compilation error I fixed some for you this time, but won t do it next time Make sure you run os161-tester m : what you get will be your final mark! Will do a brief midterm review in next Monday s lecture 2/10/13 2 1

2 Higher-Level Synchronization We looked at using locks to provide mutual exclusion Locks work, but they have some drawbacks when critical regions are long Spinlocks inefficient Disabling interrupts can miss or delay important events Instead, we want synchronization mechanisms that Block waiters Leave interrupts enabled inside the critical section Look at two common high-level mechanisms Semaphores: binary (mutex) and counting Monitors: mutexes and condition variables Use them to solve common synchronization problems 2/10/13 3 Semaphores Semaphores are an abstract data type that provide mutual exclusion to critical region Semaphores can also be used as atomic counters More later Semaphores are integers that support two operations: wait(semaphore): decrement, block until semaphore is open Also P(), after the Dutch word for test, or down() signal(semaphore): increment, allow another thread to enter Also V() after the Dutch word for increment, or up() That's it! No other operations not even just reading its value exist P and V are probably the most unintuitive names you encounter in this course and you have Edsger W. Dijkstra to thank to Semaphore safety property: the semaphore value is always greater than or equal to 0 2/10/13 4 2

4 Using Semaphores Use is similar to our locks, but semantics are different struct Semaphore { int value; Queue q; S; withdraw (account, amount) { P(S); balance = get_balance(account); balance = balance amount; put_balance(account, balance); V(S); return balance; Threads block critical section P(S); balance = get_balance(account); balance = balance amount; P(S); P(S); put_balance(account, balance); V(S); V(S); It is undefined which thread runs after a signal V(S); 2/10/13 7 Semaphores in OS161 P(sem) { Disable interrupts; while (sem->count == 0) { thread_sleep(sem); /* current thread will sleep on this sem */ sem->count--; Enable interrupts; V(sem) { Disable interrupts; sem->count++; thread_wakeup (sem); /* this will wake up all the threads waiting on this sem. Why wake up all threads? */ Enable interrupts; thread_sleep() assumes interrupts are disabled Note that interrupts are disabled only to enter/leave critical section How can it sleep with interrupts disabled? What happens if while (sem->count ==0) is an if (sem- >count!= 0)? 2/10/13 8 4

5 Using Semaphores We ve looked at a simple example for using synchronization Mutual exclusion while accessing a bank account Now we re going to use semaphores to look at more interesting examples Readers/Writers Bounded Buffers 2/10/13 9 Readers/Writers Problem Readers/Writers Problem: An object is shared among several threads Some threads only read the object, others only write it We can allow multiple readers but only one writer Let #r be the number of readers, #w be the number of writers Safety: (#r 0) (0 #w 1) ((#r > 0) (#w = 0)) How can we use semaphores to control access to the object to implement this protocol? 2/10/

9 Problem: Starvation What if a writer is waiting, but readers keep coming, the writer is starved If you are interested, think how to solve this problem 2/10/13 17 Review of last lecture Semaphore P(semaphore): while (semaphore == 0) sleep(semaphore); semaphore--; V(semaphore): semaphore++; wakeup (semaphore); Binary semaphore (mutex) and counting semaphore Using mutex to solve reader/writer problem 2/10/

10 Bounded Buffer Problem: There is a set of resource buffers shared by producer and consumer threads Producer inserts resources into the buffer set Output, disk blocks, memory pages, processes, etc. Consumer removes resources from the buffer set Whatever is generated by the producer Producer and consumer execute at different rates No serialization of one behind the other Tasks are independent (easier to think about) The buffer set allows each to run without explicit handoff Safety: Sequence of consumed values is prefix of sequence of produced values If nc is number consumed, np number produced, and N the size of the buffer, then 0 np - nc N 2/10/13 19 Bounded Buffer (2) Use three semaphores: empty count of empty buffers Counting semaphore empty = N (np nc) full count of full buffers Counting semaphore np - nc = full mutex mutual exclusion to shared set of buffers Binary semaphore 2/10/

11 Bounded Buffer (3) Semaphore mutex = 1; // mutual exclusion to shared set of buffers Semaphore empty = N; // count of empty buffers (all empty to start) Semaphore full = 0; // count of full buffers (none full to start) producer { while (1) { Produce new resource; P(empty); // wait for empty buffer P(mutex); // lock buffer list Add resource to an empty buffer; V(mutex); // unlock buffer list V(full); // note a full buffer consumer { while (1) { P(full); // wait for a full buffer P(mutex); // lock buffer list Remove resource from a full buffer; V(mutex); // unlock buffer list V(empty); // note an empty buffer Consume resource; 2/10/13 21 Bounded Buffer (4) Consumer decrements FULL and blocks when buffer has no item since the semaphore FULL is at 0 2/10/

12 Bounded Buffer (5) Why we need both empty and full semaphores? Semaphore mutex = 1; // mutual exclusion to shared set of buffers Semaphore empty = N; // count of empty buffers (all empty to start) Semaphore full = 0; // count of full buffers (none full to start) producer { while (1) { Produce new resource; P(empty); // wait for empty buffer P(mutex); // lock buffer list Add resource to an empty buffer; V(mutex); // unlock buffer list V(full); // note a full buffer consumer { while (1) { P(full); // wait for a full buffer P(mutex); // lock buffer list Remove resource from a full buffer; V(mutex); // unlock buffer list V(empty); // note an empty buffer Consume resource; More consumers remove resource than actually produced! 2/10/13 23 Bounded Buffer (6) Why need the mutex at all? Reader-Writer and Bounded Buffer are classic examples of synchronization problems 2/10/

13 Semaphore Questions Are there any problems that can be solved with counting semaphores that cannot be solved with mutex semaphores? If a system provides only mutex semaphores, can you use it to implement a counting semaphores? When to use counting semaphore? Problem needs a counter The maximum value is known (bouned) 2/10/13 25 Possible Deadlocks with Semaphores Example: Thread 1: P(S); P(Q);.... V(Q); V(S); Thread 2: share two mutex semaphores S and Q S:= 1; Q:=1; P(Q); P(S);.... V(S); V(Q); 2/10/

14 Semaphore Summary Semaphores can be used to solve any of the traditional synchronization problems However, they have some drawbacks They are essentially shared global variables Can potentially be accessed anywhere in program No connection between the semaphore and the data being controlled by the semaphore No control or guarantee of proper usage Sometimes hard to use and prone to bugs Another approach: Use programming language support 2/10/13 27 Monitors A monitor is a programming language construct that controls access to shared data Synchronization code added by compiler, enforced at runtime Why is this an advantage? A monitor is a module that encapsulates Shared data structures Procedures that operate on the shared data structures Synchronization between concurrent threads that invoke the procedures A monitor protects its data from unstructured access It guarantees that threads accessing its data through its procedures interact only in legitimate ways 2/10/

15 Monitor Semantics A monitor guarantees mutual exclusion Only one thread can execute any monitor procedure at any time (the thread is in the monitor ) If a second thread invokes a monitor procedure when a first thread is already executing one, it blocks So the monitor has to have a wait queue If a thread within a monitor blocks, another one can enter Condition Variable What are the implications in terms of parallelism in monitor? 2/10/13 29 Account Example Monitor account { double balance; double withdraw(amount) { balance = balance amount; return balance; Threads block waiting to get into monitor withdraw(amount) balance = balance amount; withdraw(amount) withdraw(amount) return balance (and exit) balance = balance amount return balance; When first thread exits, another can enter. Which one is undefined. Hey, that was easy balance = balance amount; return balance; But what if a thread wants to wait inside the monitor? 2/10/

16 Condition Variables A condition variable is associated with a condition needed for a thread to make progress once it is in the monitor. Monitor M {... monitored variables Condition c; void enter_mon (...) { if (extra property not true) wait(c); do what you have to do if (extra property true) signal(c); waits outside of the monitor's mutex brings in one thread waiting on condition 2/10/13 31 Condition Variables Condition variables support three operations: Wait release monitor lock, wait for C/V to be signaled So condition variables have wait queues, too Signal wakeup one waiting thread Broadcast wakeup all waiting threads Condition variables are not boolean objects if (condition_variable) then does not make sense if (num_resources == 0) then wait(resources_available) does An example will make this more clear 2/10/

17 Monitor Bounded Buffer Monitor bounded_buffer { Resource buffer[n]; // Variables for indexing buffer // monitor invariant involves these vars Condition not_full; // space in buffer Condition not_empty; // value in buffer void put_resource (Resource R) { if (buffer array is full) wait(not_full); Add R to buffer array; signal(not_empty); Resource get_resource() { if (buffer array is empty) wait(not_empty); Get resource R from buffer array; signal(not_full); return R; // end monitor What happens if no threads are waiting when signal is called? Signal is lost 2/10/13 33 Monitor Queues Monitor bounded_buffer { Condition not_full; other variables Condition not_empty; void put_resource () { wait(not_full) signal(not_empty) Resource get_resource () { Waiting to enter Waiting on condition variables Executing inside the monitor 2/10/

18 Condition Vars!= Semaphores Condition variables!= semaphores However, they each can be used to implement the other Access to the monitor is controlled by a lock wait() blocks the calling thread, and gives up the lock To call wait, the thread has to be in the monitor (hence has lock) Semaphore::P just blocks the thread on the queue signal() causes a waiting thread to wake up If there is no waiting thread, the signal is lost Semaphore::V increases the semaphore count, allowing future entry even if no thread is waiting Condition variables have no history 2/10/13 35 Locks and Condition Vars In OS161, we don t have monitors But we want to be able to use condition variables So we isolate condition variables and make them independent (not associated with a monitor) Instead, we have to associate them with a lock (mutex) Now, to use a condition variable Threads must first acquire the lock (mutex) CV::Wait releases the lock before blocking, acquires it after waking up 2/10/

19 Signal Semantics There are two flavors of monitors that differ in the scheduling semantics of signal() Hoare monitors (original) signal() immediately switches from the caller to a waiting thread The condition that the waiter was anticipating is guaranteed to hold when waiter executes Mesa monitors (Mesa, Java) signal() places a waiter on the ready queue, but signaler continues inside monitor Condition is not necessarily true when waiter runs again Returning from wait() is only a hint that something changed Must recheck conditional case 2/10/13 37 Hoare vs. Mesa Monitors Hoare if (empty) wait(condition); Mesa while (empty) wait(condition); Tradeoffs Mesa monitors easier to use, more efficient Fewer context switches, easy to support broadcast Hoare monitors leave less to chance Easier to reason about the program 2/10/

21 Monitor Readers and Writers Is there any priority between readers and writers? What if you wanted to ensure that a waiting writer would have priority over new readers? 2/10/13 41 Summary Semaphores P()/V() implement blocking mutual exclusion Also used as atomic counters (counting semaphores) Can be inconvenient to use Monitors Synchronizes execution within procedures that manipulate encapsulated data shared among procedures Only one thread can execute within a monitor at a time Relies upon high-level language support Condition variables Used by threads as a synchronization point to wait for events Inside monitors 2/10/

22 Happy Lunar New Year! 2/10/

### CS 318 Principles of Operating Systems

CS 318 Principles of Operating Systems Fall 2017 Lecture 7: Semaphores and Monitors Ryan Huang Higher-Level Synchronization We looked at using locks to provide mutual exclusion Locks work, but they have

### CSE 120 Principles of Operating Systems Spring 2016

CSE 120 Principles of Operating Systems Spring 2016 Condition Variables and Monitors Monitors A monitor is a programming language construct that controls access to shared data Synchronization code added

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

Semaphores CSE 451: Operating Systems Spring 2013 Module 8 Semaphores, Condition Variables, and Monitors Ed Lazowska lazowska@cs.washington.edu Allen Center 570 Semaphore = a synchronization primitive

### CSE 120. Fall Lecture 6: Semaphores. Keith Marzullo

CSE 120 Principles of Operating Systems Fall 2007 Lecture 6: Semaphores Keith Marzullo Announcements Homework #2 out Homework #1 almost graded... Discussion session on Wednesday will entertain questions

### There are 8 total numbered pages, 6 Questions. You have 60 minutes. Budget your time carefully!

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING MIDTERM EXAMINATION, March, 2017 Third Year Materials ECE344H1 - Operating Systems Calculator Type: 2 Exam Type: A Examiner D. Yuan Please

### Semaphores and Monitors: High-level Synchronization Constructs

1 Synchronization Constructs Synchronization Coordinating execution of multiple threads that share data structures Semaphores and Monitors High-level Synchronization Constructs A Historical Perspective

### Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Semaphores Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu) Synchronization

### 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

### 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.

### Semaphores INF4140. Lecture 3. 0 Book: Andrews - ch.04 ( ) INF4140 ( ) Semaphores Lecture 3 1 / 34

Semaphores INF4140 13.09.12 Lecture 3 0 Book: Andrews - ch.04 (4.1-4.4) INF4140 (13.09.12 ) Semaphores Lecture 3 1 / 34 Overview Last lecture: Locks and Barriers (complex techniques) No clear difference

### Synchronization 1. Synchronization

Synchronization 1 Synchronization key concepts critical sections, mutual exclusion, test-and-set, spinlocks, blocking and blocking locks, semaphores, condition variables, deadlocks reading Three Easy Pieces:

### Synchronization. Disclaimer: some slides are adopted from the book authors slides 1

Synchronization Disclaimer: some slides are adopted from the book authors slides 1 Recap Synchronization instructions test&set, compare&swap All or nothing Spinlock Spin on wait Good for short critical

### Semaphore. Originally called P() and V() wait (S) { while S <= 0 ; // no-op S--; } signal (S) { S++; }

Semaphore Semaphore S integer variable Two standard operations modify S: wait() and signal() Originally called P() and V() Can only be accessed via two indivisible (atomic) operations wait (S) { while

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

Introducing Monitors Separate the concerns of mutual exclusion and conditional synchronization What is a monitor? " One lock, and " Zero or more condition variables for managing concurrent access to shared

### Synchronization 1. Synchronization

Synchronization 1 Synchronization key concepts critical sections, mutual exclusion, test-and-set, spinlocks, blocking and blocking locks, semaphores, condition variables, deadlocks reading Three Easy Pieces:

### 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

### 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

### Concurrency Control. Synchronization. Brief Preview of Scheduling. Motivating Example. Motivating Example (Cont d) Interleaved Schedules

Brief Preview of Scheduling Concurrency Control Nan Niu (nn@cs.toronto.edu) CSC309 -- Summer 2008 Multiple threads ready to run Some mechanism for switching between them Context switches Some policy for

### Synchronization. Heechul Yun. Disclaimer: some slides are adopted from the book authors and Dr. Kulkani

Synchronization Heechul Yun Disclaimer: some slides are adopted from the book authors and Dr. Kulkani 1 Synchronization Spinlock Recap Implement using h/w instructions (e.g., test-and-set) Mutex Sleep

### 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

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

Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois 1 Synchronization primitives Mutex locks Used for exclusive access to a shared resource (critical section) Operations:

### 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

### Synchronization Basic Problem:

Synchronization Synchronization Basic Problem: If two concurrent processes are accessing a shared variable, and that variable is read, modified, and written by those processes, then the variable must be

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

Lecture Topics Today: Concurrency (Stallings, chapter 5.1-5.4, 5.7) Next: Exam #1 1 Announcements Self-Study Exercise #5 Project #3 (due 9/28) Project #4 (due 10/12) 2 Exam #1 Tuesday, 10/3 during lecture

### CS370 Operating Systems

CS370 Operating Systems Colorado State University Yashwant K Malaiya Fall 2017 Lecture 12 Slides based on Text by Silberschatz, Galvin, Gagne Various sources 1 1 FAQ 2 Mutex vs Semaphore Mutex is binary,

### 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

### 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

### Topic 4: Synchronization with Semaphores

CS 414 : Operating Systems UNIVERSITY OF VIRGINIA Department of Computer Science Fall 2005 Topic 4: Synchronization with Semaphores Readings for this topic: Sections 6.1-6.6 The too-much-milk solution

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

Administrivia Assignments 0 & 1 Class contact for the next two weeks Next week midterm exam project review & discussion (Chris Chambers) Following week Memory Management (Wuchi Feng) 1 CSE 513 Introduction

### Operating Systems. Synchronization

Operating Systems Fall 2014 Synchronization Myungjin Lee myungjin.lee@ed.ac.uk 1 Temporal relations Instructions executed by a single thread are totally ordered A < B < C < Absent synchronization, instructions

### Semaphores. Mutual Exclusion. Inference Rules. Fairness: V may release a waiting process. Weakly fair, Strongly fair, or FIFO

Semaphores A shared integer variable, s, initialized to init, and manipulated only by two operations: pass (proberen): P(s) df = await(s > 0)s = s 1 1 Fairness: V may release a waiting process Weakly fair,

### Condition Variables. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

Condition Variables Jinkyu Jeong (jinkyu@skku.edu) Computer Systems Laboratory Sungkyunkwan University http://csl.skku.edu EEE3052: Introduction to Operating Systems, Fall 2017, Jinkyu Jeong (jinkyu@skku.edu)

### Synchronization. CS61, Lecture 18. Prof. Stephen Chong November 3, 2011

Synchronization CS61, Lecture 18 Prof. Stephen Chong November 3, 2011 Announcements Assignment 5 Tell us your group by Sunday Nov 6 Due Thursday Nov 17 Talks of interest in next two days Towards Predictable,

### 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

### Synchronization Primitives

Synchronization Primitives Locks Synchronization Mechanisms Very primitive constructs with minimal semantics Semaphores A generalization of locks Easy to understand, hard to program with Condition Variables

### W4118 Operating Systems. Instructor: Junfeng Yang

W4118 Operating Systems Instructor: Junfeng Yang Outline Semaphores Producer-consumer problem Monitors and condition variables 2 Semaphore motivation Problem with lock: mutual exclusion, but no ordering

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

Review: Implementation of Locks by Disabling Interrupts CS162 Operating Systems and Systems Programming Lecture 8 Readers-Writers Language Support for Synchronization September 27, 2010 Prof John Kubiatowicz

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

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

### Last Class: Synchronization

Last Class: Synchronization Synchronization primitives are required to ensure that only one thread executes in a critical section at a time. Concurrent programs Low-level atomic operations (hardware) load/store

### Atomic Instructions! Hakim Weatherspoon CS 3410, Spring 2011 Computer Science Cornell University. P&H Chapter 2.11

Atomic Instructions! Hakim Weatherspoon CS 3410, Spring 2011 Computer Science Cornell University P&H Chapter 2.11 Announcements! PA4 due next, Friday, May 13 th Work in pairs Will not be able to use slip

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

Synchronization II Today Condition Variables Semaphores Monitors and some classical problems Next time Deadlocks Condition variables Many times a thread wants to check whether a condition is true before

### 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

### 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.

### 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.

### Interprocess Communication and Synchronization

Chapter 2 (Second Part) Interprocess Communication and Synchronization Slide Credits: Jonathan Walpole Andrew Tanenbaum 1 Outline Race Conditions Mutual Exclusion and Critical Regions Mutex s Test-And-Set

### CS 471 Operating Systems. Yue Cheng. George Mason University Fall 2017

CS 471 Operating Systems Yue Cheng George Mason University Fall 2017 1 Review: Sync Terminology Worksheet 2 Review: Semaphores 3 Semaphores o Motivation: Avoid busy waiting by blocking a process execution

### CSCE 313: Introduction to Computer Systems

CSCE 313 Introduction to Computer Systems Instructor: Dr. Guofei Gu http://courses.cse.tamu.edu/guofei/csce313 Synchronization: Critical Sections & Semaphores Why? What? How? Examples The Critical Section

### The Synchronization Toolbox

The Synchronization Toolbox Mutual Exclusion Race conditions can be avoiding by ensuring mutual exclusion in critical sections. Critical sections are code sequences that are vulnerable to races. Every

### 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

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

Synchronization II: EventBarrier, Monitor, and a Semaphore COMPSCI210 Recitation 4th Mar 2013 Vamsi Thummala Check point: Mission in progress Master synchronization techniques Develop best practices for

### Synchronization Without Busy Waiting

Synchronization Without Busy Waiting The solutions we ve considered up to now, Dekker s and Peterson s algorithms and hardware testand-set all share an unpleasent attribute. processes waiting to enter

### Deadlock. Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1

Deadlock Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1 Recap: Synchronization Race condition A situation when two or more threads read and write shared

### Chapter 6 Process Synchronization

Chapter 6 Process Synchronization Cooperating Process process that can affect or be affected by other processes directly share a logical address space (threads) be allowed to share data via files or messages

### Concurrent Programming Issues & Readers/Writers

Concurrent Programming Issues & Readers/Writers 1 Summary of Our Discussions! Developing and debugging concurrent programs is hard Ø Non-deterministic interleaving of instructions! Safety: isolation and

### Quiz Answers. CS 537 Lecture 9 Deadlock. What can go wrong? Readers and Writers Monitor Example

Quiz Answers CS 537 Lecture 9 Deadlock Use of disabling interrupts Not allowed by processor --> requires system call Not safe is usermode code buggy and allowed by processor Locking Just lock manipulation

### MULTITHREADING AND SYNCHRONIZATION. CS124 Operating Systems Fall , Lecture 10

MULTITHREADING AND SYNCHRONIZATION CS124 Operating Systems Fall 2017-2018, Lecture 10 2 Critical Sections Race conditions can be avoided by preventing multiple control paths from accessing shared state

### Classical concurrency control: topic overview 1 In these lectures we consider shared writeable data in main memory

Classical concurrency control: topic overview 1 In these lectures we consider shared writeable data in main memory Controlling access by concurrent processes to shared writeable data has been studied as

### 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

CSCI-GA.3033-017 Special Topics: Multicore Programming Lecture 5 Threads and Pthreads II Christopher Mitchell, Ph.D. cmitchell@cs.nyu.edu http://z80.me Context We re exploring the layers of an application

### Synchronization. Race Condition. The Critical-Section Problem Solution. The Synchronization Problem. Typical Process P i. Peterson s Solution

Race Condition Synchronization CSCI 315 Operating Systems Design Department of Computer Science A race occurs when the correctness of a program depends on one thread reaching point x in its control flow

### Writing Parallel Programs COMP360

Writing Parallel Programs COMP360 We stand at the threshold of a many core world. The hardware community is ready to cross this threshold. The parallel software community is not. Tim Mattson principal

### Chapter 7: Process Synchronization. Background. Illustration

Chapter 7: Process Synchronization Background The Critical-Section Problem Synchronization Hardware Semaphores Classical Problems of Synchronization Critical Regions Monitors Synchronization in Solaris

### Deadlock. Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1

Deadlock Disclaimer: some slides are adopted from Dr. Kulkarni s and book authors slides with permission 1 Recap: Synchronization Race condition A situation when two or more threads read and write shared

### 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

### 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

### Semaphores (by Dijkstra)

CSCI 4401 Principles of Operating Systems I Process Synchronization II: Classic Problems Vassil Roussev vassil@cs.uno.edu Semaphores (by Dijkstra) A higher-level way of doing synchronization between threads/processes

### Operating systems and concurrency (B08)

Operating systems and concurrency (B08) David Kendall Northumbria University David Kendall (Northumbria University) Operating systems and concurrency (B08) 1 / 20 Introduction Semaphores provide an unstructured

### EE458 - Embedded Systems Lecture 8 Semaphores

EE458 - Embedded Systems Lecture 8 Semaphores Outline Introduction to Semaphores Binary and Counting Semaphores Mutexes Typical Applications RTEMS Semaphores References RTC: Chapter 6 CUG: Chapter 9 1

### Chapter 5: Process Synchronization

Chapter 5: Process Synchronization Silberschatz, Galvin and Gagne 2013! Chapter 5: Process Synchronization Background" The Critical-Section Problem" Petersons Solution" Synchronization Hardware" Mutex

### But first... Re: generic parking. A cyclic POSIX thread (2) Real-time Systems SMD138. Lecture 14: Real-time languages (Burns & Wellings ch.

But first... Real-time Systems SMD138 Lecture 14: Real-time languages (Burns & Wellings ch. 8 & 9) As it happens, Cygwin the PC side lab programming environment doesn t support timer_create() and timer_settime()

### 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

### 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

### Process Co-ordination OPERATING SYSTEMS

OPERATING SYSTEMS Prescribed Text Book Operating System Principles, Seventh Edition By Abraham Silberschatz, Peter Baer Galvin and Greg Gagne 1 PROCESS - CONCEPT Processes executing concurrently in the

### Two Types of Semaphores

Two Types of Semaphores Counting semaphore integer value can range over an unrestricted domain. Binary semaphore integer value can range only between 0 and 1; can be simpler to implement. Can implement

### September 23 rd, 2015 Prof. John Kubiatowicz

CS162 Operating Systems and Systems Programming Lecture 8 Locks, Semaphores, Monitors, and Quick Intro to Scheduling September 23 rd, 2015 Prof. John Kubiatowicz http://cs162.eecs.berkeley.edu Acknowledgments:

### 9/29/2014. CS341: Operating System Mid Semester Model Solution Uploaded Semaphore ADT: wait(), signal()

CS341: Operating System Mid Semester Model Solution Uploaded Semaphore ADT: wait(), signal() Lect23: 30 th Sept 2014 Dr. A. Sahu Dept of Comp. Sc. & Engg. Indian Institute of Technology Guwahati Classical

### Synchronization. CSCI 5103 Operating Systems. Semaphore Usage. Bounded-Buffer Problem With Semaphores. Monitors Other Approaches

Synchronization CSCI 5103 Operating Systems Monitors Other Approaches Instructor: Abhishek Chandra 2 3 Semaphore Usage wait(s) Critical section signal(s) Each process must call wait and signal in correct

### Linux kernel synchronization. Don Porter CSE 506

Linux kernel synchronization Don Porter CSE 506 The old days Early/simple OSes (like JOS): No need for synchronization All kernel requests wait until completion even disk requests Heavily restrict when

### Semaphores (and Eventcounts) Otto J. Anshus University of {Tromsø, Oslo}

Semaphores (and Eventcounts) Otto J. Anshus University of {Tromsø, Oslo} The Wa (Wawa) at Princeton See the too much milk problem last week Wawa http://www.wawa.com/ http://www.absoluteastronomy.com/encyclopedia/w/wa/wawa_food_markets.htm

### Week 3. Locks & Semaphores

Week 3 Locks & Semaphores Synchronization Mechanisms Locks Very primitive constructs with minimal semantics Semaphores A generalization of locks Easy to understand, hard to program with Condition Variables

### CS162 Operating Systems and Systems Programming Lecture 7. Mutual Exclusion, Semaphores, Monitors, and Condition Variables

CS162 Operating Systems and Systems Programming Lecture 7 Mutual Exclusion, Semaphores, Monitors, and Condition Variables September 22, 2010 Prof John Kubiatowicz http://insteecsberkeleyedu/~cs162 Review:

### Java Monitors. Parallel and Distributed Computing. Department of Computer Science and Engineering (DEI) Instituto Superior Técnico.

Java Monitors Parallel and Distributed Computing Department of Computer Science and Engineering (DEI) Instituto Superior Técnico October 19, 2010 Monteiro, Costa (DEI / IST) Parallel and Distributed Computing

### Synchronization Spinlocks - Semaphores

CS 4410 Operating Systems Synchronization Spinlocks - Semaphores Summer 2013 Cornell University 1 Today How can I synchronize the execution of multiple threads of the same process? Example Race condition

### Monitors (Deprecated)

D Monitors (Deprecated) Around the time concurrent programming was becoming a big deal, objectoriented programming was also gaining ground. Not surprisingly, people started to think about ways to merge

### OS Process Synchronization!

OS Process Synchronization! Race Conditions! The Critical Section Problem! Synchronization Hardware! Semaphores! Classical Problems of Synchronization! Synchronization HW Assignment! 3.1! Concurrent Access

### Synchronization COMPSCI 386

Synchronization COMPSCI 386 Obvious? // push an item onto the stack while (top == SIZE) ; stack[top++] = item; // pop an item off the stack while (top == 0) ; item = stack[top--]; PRODUCER CONSUMER Suppose

### 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

### Synchronization Classic Problems

CS 4410 Operating Systems Synchronization Classic Problems Summer 2013 Cornell University 1 Today What practical problems can we solve with semaphores? Bounded-Buffer Problem Producer-Consumer Problem

### Chapter 6: Process Synchronization

Module 6: Process Synchronization Chapter 6: Process Synchronization Background! The Critical-Section Problem! Peterson s Solution! Synchronization Hardware! Semaphores! Classic Problems of Synchronization!

### PROJECT 6: PINTOS FILE SYSTEM. CS124 Operating Systems Winter , Lecture 25

PROJECT 6: PINTOS FILE SYSTEM CS124 Operating Systems Winter 2015-2016, Lecture 25 2 Project 6: Pintos File System Last project is to improve the Pintos file system Note: Please ask before using late tokens

### 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:

### COP 4225 Advanced Unix Programming. Synchronization. Chi Zhang

COP 4225 Advanced Unix Programming Synchronization Chi Zhang czhang@cs.fiu.edu 1 Cooperating Processes Independent process cannot affect or be affected by the execution of another process. Cooperating

### Concurrency: Deadlock and Starvation. Chapter 6

Concurrency: Deadlock and Starvation Chapter 6 Deadlock Permanent blocking of a set of processes that either compete for system resources or communicate with each other Involve conflicting needs for resources

### Process Synchronization and Cooperation

January 13, 2000 ECS 251 Winter 2000 Page 1 Process Synchronization and Cooperation 1. Parallelism a. concurrent vs. sequential b. logical vs. physical concurrency c. process creation: static vs. dynamic

### Background. Module 6: Process Synchronization. Bounded-Buffer (Cont.) Bounded-Buffer. Background

Module 6: Process Synchronization Background Background The Critical-Section Problem Synchronization Hardware Semaphores Classical Problems of Synchronization Critical Regions Monitors Synchronization

### Concurrency pros and cons. Concurrent Programming Problems. Linked list example. Linked list example. Mutual Exclusion. Concurrency is good for users

Concurrency pros and cons Con Programming Problems OS Spring 2011 Concurrency is good for users One of the reasons for multiprogramming Working on the same problem, simultaneous execution of programs,