CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Synchronization: Semaphore

Size: px
Start display at page:

Download "CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Synchronization: Semaphore"

Transcription

1 CSE120 Principes of Operating Systems Prof Yuanyuan (YY) Zhou Synchronization:

2 Synchronization Needs Two synchronization needs Mutua excusion Whenever mutipe threads access a shared data, you need to worry about protection for mutua excusion Coordination (one wait for the other to finish something, e.g. produce the data, free the buffer, etc) 2

3 guard is protecting goba variabe fag q Spinock.acquire(&m->guard) Spinock.reease(&m->guard) 3

4 Higher-Leve Synchronization We ooked at using ocks to provide mutua excusion Those ocks work, but they have some drawbacks when critica sections are ong Spinocks inefficient Instead, we want synchronization mechanisms that Bock waiters Leave interrupts enabed inside the critica section Look at two common high-eve mechanisms s: binary and counting Monitors and condition variabes Use them to sove common synchronization probems 4

5 s s are an abstract data type that provide mutua excusion to critica sections s can aso be used as atomic counters More ater s are integers that support two operations: P(semaphore): decrement, bock the caing thread unti semaphore is open, i.e. the integer is greater than 0 Aso Wait(), or down() V(semaphore): increment, aow another thread to enter. If there is a thread is bocked, wake up this thread. Aso Signa(), or up() That's it! No other operations not even just reading its vaue exist 5 safety property: the semaphore vaue is aways greater than or equa to 0

6 Bocking in s Associated with each semaphore is a queue of waiting processes When P() is caed by a thread: If semaphore is open (>0), thread continues If semaphore is cosed (==0), thread bocks on queue Then V() opens the semaphore: If a thread is waiting on the queue, the thread is unbocked If no threads are waiting on the queue, the signa is remembered for the next thread by increment the counter In other words, V() has history (c.f., condition vars ater) This history is a counter 6

7 Functionaity (NOT impementation) P( s){ If (s==0) bocked in a queue; /* wait unti s>0 */ s=s-1; V( s){ s=s+1; if (someone is waiting in a queue) wakeup one from the queue; 7 Init( s, int v){ s=v;

8 Types s come in two types Binary semaphore (vaue can be ony 1 or 0, some referred it as mutex) Represents singe access to a resource Guarantees mutua excusion to a critica section simiar to ocks with a subte difference: the former can remember when you do V(sem) when sem=0 vs do unock() if no thread has the ock) Counting semaphore Represents a resource with many units avaiabe, or a resource that aows certain kinds of unsynchronized concurrent access (e.g., reading) Mutipe threads can pass the semaphore Number of threads determined by the semaphore count You can use one type to impement the other 8

9 Counter 2 anes 9

10 Animation Video wlcqe In this video, wait() is P() and signa is V() 10

11 Using s Mutex is simiar to our ocks, but semantics are different struct { int vaue; Queue q; S; withdraw (account, amount) { P(S); baance = get_baance(account); baance = baance amount; put_baance(account, baance); V(S); return baance; Threads bock critica section P(S); baance = get_baance(account); baance = baance amount; P(S); P(S); put_baance(account, baance); V(S); V(S); 11 It is undefined which thread runs after a signa V(S);

12 Exercise Using semaphores to aow robots to attend an exam: Ony 10 seats, but 100 robots If a robot comes to the cassroom, if there is an avaiabe seat, it takes the seat; otherwise, wait outside uness another robot eaves the room; Every robot sits in the seat for ony 30min to finish the exam, and then eaves the room Impement the code (steps) for every robot to foow 12

13 Cassic Synchronization probems We ve ooked at a simpe exampe for using synchronization Mutua excusion whie accessing a bank account Now we re going to use semaphores to ook at more interesting exampes Readers/Writers Bounded Buffers Santa cause probem (youtube video) 13

14 Readers/Writers Probem Readers/Writers Probem: An object is shared among severa threads Some threads ony read the object, others ony write it We can aow mutipe readers but ony one writer How can we use semaphores to contro access to the object to impement this protoco? Use three variabes int readcount number of threads reading object mutex contro access to readcount w_or_r excusive writing or reading 14

15 First Attempt w_or_r=1; Reader{ P(w_or_r); // ock out writers read; V(w_or_r); // up for grabs Does it work? Why? writer { P(w_or_r); // ock out readers Write; V(w_or_r); // up for grabs 15

16 Second Attempt w_or_r=1; int readcount; //record #readers 16 Reader{ readcount++; if (readcount == 1){ P(w_or_r); // ock out writers read; readcount--; if (readcount == 0){ V(w_or_r); // up for grabs writer { P(w_or_r); // ock out readers Write; V(w_or_r); // up for grabs Does it work? Why? Is readcount a shared data? Who protects it?

17 Readers/Writers Rea Soution Use three variabes int readcount number of threads reading object mutex Guard access to readcount w_or_r excusive writing or reading 17

18 Readers/Writers // number of readers int readcount = 0; // mutua excusion to readcount mutex = 1; // excusive writer or reader w_or_r = 1; writer { P(w_or_r); // ock out readers Write; V(w_or_r); // up for grabs reader { P(mutex); // ock readcount readcount ++; // one more reader if (readcount == 1) P(w_or_r); // synch w/ writers V(mutex); // unock readcount Read; P(mutex); // ock readcount readcount --; // one ess reader if (readcount == 0) V(w_or_r); // up for grabs V(mutex); // unock readcount I wi give you 2-3 minutes to discuss it with someone next to you 18

19 Readers/Writers Notes w_or_r provides mutex between readers and writers, and aso between mutipe writers Why do readers use mutex (binary semaphore)? What if V() is above if (readcount == 1)? Why do we need if(readcount==1)? Why do we need if(readcount==0)? 19

20 But it sti has a probem // number of readers int readcount = 0; // mutua excusion to readcount mutex = 1; // excusive writer or reader w_or_r = 1; writer { P(w_or_r); // ock out readers Write; V(w_or_r); // up for grabs reader { P(mutex); // ock readcount readcount ++; // one more reader if (readcount == 1) P(w_or_r); // synch w/ writers V(mutex); // unock readcount Read; P(mutex); // ock readcount readcount --; // one ess reader if (readcount == 0) V(w_or_r); // up for grabs V(mutex); // unock readcount 20

21 Probem: Starvation What if a writer is waiting, but readers keep coming, the writer is starved 21

22 Bounded Buffer Probem: There is a set of resource buffers shared by producer and consumer threads Producer inserts resources into the buffer set Output, disk bocks, 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 seriaization of one behind the other Tasks are independent (easier to think about) The buffer set aows each to run without expicit handoff 22

23 Bounded Buffer (2) Use three semaphores: empty count of empty buffers Counting semaphore empty = N (np-nc) fu count of fu buffers Counting semaphore np - nc = fu mutex mutua excusion to shared set of buffers Binary semaphore 23

24 Bounded Buffer (3) mutex = 1; // mutua excusion to shared set of buffers empty = N; // count of empty buffers (a empty to start) fu = 0; // count of fu buffers (none fu to start) producer { whie (1) { Produce new resource; P(empty); // wait for empty buffer P(mutex); // ock buffer ist Add resource to an empty buffer; V(mutex); // unock buffer ist V(fu); // note a fu buffer consumer { whie (1) { P(fu); // wait for a fu buffer P(mutex); // ock buffer ist Remove resource from a fu buffer; V(mutex); // unock buffer ist V(empty); // note an empty buffer Consume resource; 24

25 Bounded Buffer (4) 25 Consumer decrements FULL and Bocks when buffer has no item Since the semaphore FULL is at 0

26 Bounded Buffer (5) Why need the mutex at a? Where are the critica sections? What happens if operations on mutex and fu/empty are switched around? The pattern of P/V on fu/empty is a common construct often caed an interock Why V(fu) and V(empty)? Producer-Consumer and Bounded Buffer are cassic exampes of synchronization probems 26

27 Youtube Video for Bounded Buffer Ts 27

28 Possibe Deadocks with s Exampe: P0 P1 share two mutex semaphores S and Q S:= 1; Q:=1; P(S); P(Q);.. V(S); V(Q); P(Q); P(S); V(Q); V(S); 28

29 Be Carefu When Using s // Vioation of Mutua Excusion V(mutex); critica section P(mutex); // Deadock Situation P(mutex); critica section P(mutex); // Vioation of Mutua Excusion critica section V(mutex); 29

30 Summary s can be used to sove any of the traditiona synchronization probems However, they have some drawbacks They are essentiay shared goba variabes Can potentiay be accessed anywhere in program No connection between the semaphore and the data being controed by the semaphore Used both for critica sections (mutua excusion) and coordination (scheduing) Note that I had to use comments in the code to distinguish No contro or guarantee of proper usage Sometimes hard to use and prone to bugs 30

31 Monitors 31 A monitor is a programming anguage construct that contros access to shared data Synchronization code added by compier, enforced at runtime Why is this an advantage? A monitor is a modue that encapsuates 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 unsynchronized access It guarantees that threads accessing its data through its procedures interact ony in egitimate ways

32 Monitor Semantics A monitor guarantees mutua excusion Ony 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 aready executing one, it bocks So the monitor has to have a wait queue If a thread within a monitor bocks, another one can enter What are the impications in terms of paraeism in monitor? 32

33 Account Exampe Monitor account { doube baance; doube withdraw(amount) { baance = baance amount; return baance; Threads bock waiting to get into monitor withdraw(amount) baance = baance amount; withdraw(amount) withdraw(amount) return baance (and exit) baance = baance amount return baance; When first thread exits, another can enter. Which one is undefined. baance = baance amount; return baance; Hey, that was easy But what if a thread wants to wait inside the monitor? 33

34 Condition Variabes A condition variabe is associated with a condition needed for a thread to make progress Monitor M {... monitored variabes Condition c; void enter_mon (...) { if (extra property not true) wait(c); do what you have to do if (extra property true) signa(c); waits outside of the monitor's mutex brings in one thread waiting on condition 34

35 Condition Variabes Condition variabes support three operations: Wait reease monitor ock, wait for C/V to be signaed So condition variabes have wait queues, too Signa wakeup one waiting thread Broadcast wakeup a waiting threads Condition variabes are not booean objects if (condition_variabe) then does not make sense if (num_resources == 0) then wait(resources_avaiabe) does An exampe wi make this more cear 35

36 Condition Variabes Condition variabes are NOT conditions So don t EVER do: if (conditionavariabe){ 36 Instead, it is a way for one thread to wait (if some resource is not avaiabe), and some other thread to wake it up once the resource becomes avaiabe Seep Wake (aso caed as signa ) Wakea (or signaa )

37 Condition Variabe & Lock Condition variabe doesn t repace ock, instead it compiments ock Seep(condition, ock) or Wait(condition, ock) First reease the ock, put the thread into the queue of the condition, if waking up, re-aquiring the ock Once seep returns, it is awaken by some other thread, and it aso hods the ock Wake(condition) or Signa(condition): Wake up a thread waiting on the condition (queue) Some systems use a different name such as Signa(condition) or Notify(condition) Wakea(condition) or Broadcast(condition) Wake a the thread waiting on the condition (queue) Some systems may use a different name such as SignaA(condition), or NotifyA(condition) 37

38 Monitor Bounded Buffer Monitor bounded_buffer { Resource buffer[n]; // Variabes for indexing buffer // monitor invariant invoves these vars Condition not_fu; // space in buffer Condition not_empty; // vaue in buffer void put_resource (Resource R) { if (buffer array is fu) wait(not_fu); Add R to buffer array; signa(not_empty); Resource get_resource() { if (buffer array is empty) wait(not_empty); Get resource R from buffer array; signa(not_fu); return R; // end monitor 38 What happens if no threads are waiting when signa is caed? Signa is ost

39 Monitor Queues Monitor bounded_buffer { Condition not_fu; other variabes Condition not_empty; void put_resource () { wait(not_fu) signa(not_empty) Resource get_resource () { Waiting to enter Waiting on condition variabes Executing inside the monitor 39

40 Condition Vars!= s Monitor with Condition variabes!= semaphores But they can impement each other Access to the monitor is controed by a ock wait() bocks the caing thread, and gives up the ock To ca wait, the thread has to be in the monitor (hence has ock) ::P just bocks the thread on the queue signa() causes a waiting thread to wake up If there is no waiting thread, the signa is ost ::V() increases the semaphore count, aowing future entry even if no thread is waiting Condition variabes have no history 40

41 Signa Semantics There are two favors of monitors that differ in the scheduing semantics of signa() Hoare monitors (origina) signa() immediatey switches from the caer to a waiting thread The condition that the waiter was anticipating is guaranteed to hod when waiter executes Signaer must restore monitor invariants before signaing Mesa monitors (Mesa, Java) signa() paces a waiter on the ready queue, but signaer continues inside monitor Condition is not necessariy true when waiter runs again Returning from wait() is ony a hint that something changed Must recheck conditiona case 41

42 Hoare vs. Mesa Monitors Hoare if (empty) Mesa wait(condition); whie (empty) wait(condition); Tradeoffs Mesa monitors easier to use, more efficient Fewer context switches, easy to support broadcast Hoare monitors eave ess to chance Easier to reason about the program 42

43 Monitor Readers and Writers Write with just wait() wi be safe, maybe not ive - why? Starvation Monitor RW { int nr = 0, nw = 0; Condition canread, canwrite; 43 void StartRead () { whie (nw!= 0) do wait(canread); nr++; void EndRead () { nr--; if (nr==0) signa(canwrite) void StartWrite { whie (nr!= 0 nw!= 0) do wait(canwrite); nw++; void EndWrite () { nw--; signa(canwrite); signa(canread); // end monitor

44 Monitor Readers and Writers Is there any priority between readers and writers? What if you wanted to ensure that a waiting writer woud have priority over new readers? 44

45 Summary s P()/V() impement bocking mutua excusion Aso used as atomic counters (counting semaphores) Can be inconvenient to use Monitors Synchronizes execution within procedures that manipuate encapsuated data shared among procedures Ony one thread can execute within a monitor at a time Reies upon high-eve anguage support Condition variabes Used by threads as a synchronization point to wait for events Inside monitors, or outside with ocks 45

46 Dining Phiosophers: an inteectua game Phiosophers eat/think Eating needs 2 forks Pick one fork at a time Possibe deadock? How to prevent deadock? 46

47 Does it sove the Dining Phiosophers Probem? 47

48 Dining Phiosophers Soution 48

49 Dining Phiosophers Soution 49

50 The Seeping Barber Probem N customer Chair One barber can cut one customer s hair at any time No customer, goes to seep 50

51 The Seeping Barber Soution (1) 51

52 The Seeping Barber Soution (2) 52

53 The Seeping Barber Soution (3) Soution to seeping barber probem. 53

54 Santa Cause Probem c4 54

Operating Systems ECE344

Operating Systems ECE344 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

More information

Opera&ng Systems ECE344

Opera&ng Systems ECE344 Opera&ng Systems ECE344 Lecture 6: Synchroniza&on (II) Semaphores and Monitors Ding Yuan Higher- Level Synchroniza&on We looked at using locks to provide mutual exclusion Locks work, but they have some

More information

CSE 153 Design of Operating Systems

CSE 153 Design of Operating Systems CSE 153 Design of Operating Systems Winter 2018 Lecture 10: Monitors Monitors A monitor is a programming language construct that controls access to shared data Synchronization code added by compiler, enforced

More information

CSE 120 Principles of Operating Systems Spring 2016

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

More information

CSE 120 Principles of Operating Systems Spring 2016

CSE 120 Principles of Operating Systems Spring 2016 CSE 120 Principles of Operating Systems Spring 2016 Semaphores and Monitors Higher-Level Synchronization We looked at using locks to provide mutual exclusion Locks work, but they have limited semantics

More information

CS 318 Principles of Operating Systems

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

More information

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Midterm Review

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Midterm Review CSE120 Principes of Operating Systems Prof Yuanyuan (YY) Zhou Midterm Review Overview The midterm Architectura support for OSes OS modues, interfaces, and structures Processes Threads Synchronization Scheduing

More information

Lecture 6 (cont.): Semaphores and Monitors

Lecture 6 (cont.): Semaphores and Monitors Project 1 Due Thursday 10/20 Lecture 6 (cont.): Semaphores and Monitors CSE 120: Principles of Operating Systems Alex C. Snoeren Higher-Level Synchronization We looked at using locks to provide mutual

More information

CS 318 Principles of Operating Systems

CS 318 Principles of Operating Systems CS 318 Principles of Operating Systems Fall 2018 Lecture 7: Semaphores and Monitors Ryan Huang Slides adapted from Geoff Voelker s lectures Administrivia HW2 is out Do the exercise to check your understanding

More information

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

CSE 451: Operating Systems Spring Module 10 Semaphores, Condition Variables, and Monitors CSE 451: Operating Systems Spring 2017 Module 10 Semaphores, Condition Variables, and Monitors John Zahorjan 2017 Gribble, Lazowska, Levy, Zahorjan, Zbikowski 1 Semaphores Semaphore = a synchronization

More information

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

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

More information

CSE 120. Fall Lecture 6: Semaphores. Keith Marzullo

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

More information

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

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

More information

Lecture 7: CVs & Scheduling

Lecture 7: CVs & Scheduling Lecture 7: CVs & Scheduling CSE 120: Principles of Operating Systems Alex C. Snoeren HW 2 Due 10/17 Monitors A monitor is a programming language construct that controls access to shared data Synchronization

More information

Semaphores. Jinkyu Jeong Computer Systems Laboratory Sungkyunkwan University

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

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

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Lecture 4: Threads

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Lecture 4: Threads CSE120 Principes of Operating Systems Prof Yuanyuan (YY) Zhou Lecture 4: Threads Announcement Project 0 Due Project 1 out Homework 1 due on Thursday Submit it to Gradescope onine 2 Processes Reca that

More information

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Scheduling

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Scheduling CSE120 Principes of Operating Systems Prof Yuanyuan (YY) Zhou Scheduing Announcement Homework 2 due on October 25th Project 1 due on October 26th 2 CSE 120 Scheduing and Deadock Scheduing Overview In discussing

More information

CSE 451: Operating Systems Winter Synchronization. Gary Kimura

CSE 451: Operating Systems Winter Synchronization. Gary Kimura CSE 451: Operating Systems Winter 2013 Synchronization Gary Kimura Synchronization Threads cooperate in multithreaded programs to share resources, access shared data structures e.g., threads accessing

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

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

CSE 120 Principles of Operating Systems Spring 2016

CSE 120 Principles of Operating Systems Spring 2016 CSE 120 Principles of Operating Systems Spring 2016 Using Semaphores and Condition Variables Higher-Level Synchronization We looked at using locks to provide mutual exclusion Locks work, but they have

More information

Concurrent programming: From theory to practice. Concurrent Algorithms 2016 Tudor David

Concurrent programming: From theory to practice. Concurrent Algorithms 2016 Tudor David oncurrent programming: From theory to practice oncurrent Agorithms 2016 Tudor David From theory to practice Theoretica (design) Practica (design) Practica (impementation) 2 From theory to practice Theoretica

More information

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

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

More information

Semaphores and Monitors: High-level Synchronization Constructs

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

More information

Lecture 3: Intro to Concurrent Processing using Semaphores

Lecture 3: Intro to Concurrent Processing using Semaphores Lecture 3: Intro to Concurrent Processing using Semaphores Semaphores; The Prucer-Consumer problem; The Dining Philosophers problem; The Readers-Writers Problem: Readers Preference Passing the Baton Ballhausen

More information

EECS 482 Introduction to Operating Systems

EECS 482 Introduction to Operating Systems EECS 482 Introduction to Operating Systems Winter 2018 Harsha V. Madhyastha Recap Multi-threaded code with monitors: Locks for mutual exclusion Condition variables for ordering constraints Every thread

More information

CS 318 Principles of Operating Systems

CS 318 Principles of Operating Systems CS 318 Principles of Operating Systems Fall 2017 Midterm Review Ryan Huang 10/12/17 CS 318 Midterm Review 2 Midterm October 17 th Tuesday 9:00-10:20 am at classroom Covers material before virtual memory

More information

Functions. 6.1 Modular Programming. 6.2 Defining and Calling Functions. Gaddis: 6.1-5,7-10,13,15-16 and 7.7

Functions. 6.1 Modular Programming. 6.2 Defining and Calling Functions. Gaddis: 6.1-5,7-10,13,15-16 and 7.7 Functions Unit 6 Gaddis: 6.1-5,7-10,13,15-16 and 7.7 CS 1428 Spring 2018 Ji Seaman 6.1 Moduar Programming Moduar programming: breaking a program up into smaer, manageabe components (modues) Function: a

More information

CSC501 Operating Systems Principles. Process Synchronization

CSC501 Operating Systems Principles. Process Synchronization CSC501 Operating Systems Principles Process Synchronization 1 Last Lecture q Process Scheduling Question I: Within one second, how many times the timer interrupt will occur? Question II: Within one second,

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

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

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Synchronization Exercise

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Synchronization Exercise CSE120 Principles of Operating Systems Prof Yuanyuan (YY) Zhou Synchronization Exercise A good review video l https://www.youtube.com/watch?v=1bvyjmgiaeu l Correction: CPU doesn t do scheduling. It is

More information

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

Deadlock and Monitors. CS439: Principles of Computer Systems September 24, 2018 Deadlock and Monitors CS439: Principles of Computer Systems September 24, 2018 Bringing It All Together Processes Abstraction for protection Define address space Threads Share (and communicate) through

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

Outline for Today. 5 Dining Philosophers. Template for Philosopher. Naive Solution. Objective: Administrative details:

Outline for Today. 5 Dining Philosophers. Template for Philosopher. Naive Solution. Objective: Administrative details: Outline for Today Objective: 5 Dining Philosophers Reader-writer problem Message Passing Administrative details: Check for demo location with grader TA s and me: come to our offices UTA s if they don t

More information

Programming Languages

Programming Languages Programming Languages Tevfik Koşar Lecture - XXVI April 27 th, 2006 1 Roadmap Shared Memory Synchronization Spin Locks Barriers Semaphores Monitors 2 1 Memory Architectures Distributed Memory Shared Memory

More information

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

Semaphores. To avoid busy waiting: when a process has to wait, it will be put in a blocked queue of processes waiting for the same event Semaphores Synchronization tool (provided by the OS) that do not require busy waiting A semaphore S is an integer variable that, apart from initialization, can only be accessed through 2 atomic and mutually

More information

Semaphores. Semaphores. Semaphore s operations. Semaphores: observations

Semaphores. Semaphores. Semaphore s operations. Semaphores: observations Semaphores Synchronization tool (provided by the OS) that do not require busy waiting A semaphore S is an integer variable that, apart from initialization, can only be accessed through 2 atomic and mutually

More information

Synchronization. Dr. Yingwu Zhu

Synchronization. Dr. Yingwu Zhu Synchronization Dr. Yingwu Zhu Synchronization Threads cooperate in multithreaded programs To share resources, access shared data structures Threads accessing a memory cache in a Web server To coordinate

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

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

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

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

More information

Critical Section Problem: Example

Critical Section Problem: Example Why?! Examples Semaphores Monitors Synchronization: Recap Reading: Silberschatz, Ch. 6 Critical Section Problem: Example Insertion of an element into a list. new curr 1. void insert(new, curr) { /*1*/

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

Process Synchronization. studykorner.org

Process Synchronization. studykorner.org Process Synchronization Semaphore Implementation Must guarantee that no two processes can execute wait () and signal () on the same semaphore at the same time The main disadvantage of the semaphore definition

More information

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

Operating Systems CMPSC 473. Synchronization February 26, Lecture 12 Instructor: Trent Jaeger Operating Systems CMPSC 473 Synchronization February 26, 2008 - Lecture 12 Instructor: Trent Jaeger Last class: Synchronization Problems and Primitives Today: Synchonization Solutions Midterm (Both Sections)

More information

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

Deadlock and Monitors. CS439: Principles of Computer Systems February 7, 2018 Deadlock and Monitors CS439: Principles of Computer Systems February 7, 2018 Last Time Terminology Safety and liveness Atomic Instructions, Synchronization, Mutual Exclusion, Critical Sections Synchronization

More information

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

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

More information

Interprocess Communication and Synchronization

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

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 9: Semaphores and Monitors Some slides from Matt Welsh Summarize Where We Are Goal: Use mutual exclusion to protect critical sections of code that

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

5 Dining Philosophers. Template for Philosopher. Naive Solution. while (food available) /*pick up forks*/ eat; /*put down forks*/ think awhile;

5 Dining Philosophers. Template for Philosopher. Naive Solution. while (food available) /*pick up forks*/ eat; /*put down forks*/ think awhile; 5 Dining Philosophers Philosopher 4 Philosopher 3 Philosopher 0 while(food available) pick up 2 adj. forks; put down forks; Philosopher 1 Philosopher 2 90 Template for Philosopher /*pick up forks*/ /*put

More information

Synchronization. CSE 2431: Introduction to Operating Systems Reading: Chapter 5, [OSC] (except Section 5.10)

Synchronization. CSE 2431: Introduction to Operating Systems Reading: Chapter 5, [OSC] (except Section 5.10) Synchronization CSE 2431: Introduction to Operating Systems Reading: Chapter 5, [OSC] (except Section 5.10) 1 Outline Critical region and mutual exclusion Mutual exclusion using busy waiting Sleep and

More information

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

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

More information

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

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

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

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

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

MCSE Training Guide: Windows Architecture and Memory

MCSE Training Guide: Windows Architecture and Memory MCSE Training Guide: Windows 95 -- Ch 2 -- Architecture and Memory Page 1 of 13 MCSE Training Guide: Windows 95-2 - Architecture and Memory This chapter wi hep you prepare for the exam by covering the

More information

Process synchronization

Process synchronization Process synchronization Frédéric Haziza Department of Computer Systems Uppsala University Spring 2008 Shared Resource Remark Sequential program use shared variables Convenience for Global

More information

Synchronization Basic Problem:

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

More information

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Advanced Memory Management

CSE120 Principles of Operating Systems. Prof Yuanyuan (YY) Zhou Advanced Memory Management CSE120 Principes of Operating Systems Prof Yuanyuan (YY) Zhou Advanced Memory Management Advanced Functionaity Now we re going to ook at some advanced functionaity that the OS can provide appications using

More information

Operating Systems (2INC0) 2017/18

Operating Systems (2INC0) 2017/18 Operating Systems (2INC0) 2017/18 Condition Synchronization (07) Dr. Courtesy of Prof. Dr. Johan Lukkien System Architecture and Networking Group Agenda Condition synchronization motivation condition variables

More information

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

CS 537 Lecture 8 Monitors. Thread Join with Semaphores. Dining Philosophers. Parent thread. Child thread. Michael Swift CS 537 Lecture 8 Monitors Michael Swift Two Classes of Synchronization Problems Uniform resource usage with simple scheduling constraints No other variables needed to express relationships Use one semaphore

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

Lecture 9: Midterm Review

Lecture 9: Midterm Review Project 1 Due at Midnight Lecture 9: Midterm Review CSE 120: Principles of Operating Systems Alex C. Snoeren Midterm Everything we ve covered is fair game Readings, lectures, homework, and Nachos Yes,

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

Silberschatz and Galvin Chapter 6

Silberschatz and Galvin Chapter 6 Silberschatz and Galvin Chapter 6 Process Synchronization CPSC 410--Richard Furuta 2/26/99 1 Topics discussed Process synchronization Mutual exclusion--hardware Higher-level abstractions Ð Semaphores Ð

More information

Critical Section Problem: Example

Critical Section Problem: Example Synchronization: Recap Why? Example The Critical Section Problem (recap!) Hardware Support for Synchronization Lock-free operations Semaphores Monitors Reading: Doeppner, Ch. 2.2.3 Critical Section Problem:

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

1995 Paper 10 Question 7

1995 Paper 10 Question 7 995 Paper 0 Question 7 Why are multiple buffers often used between producing and consuming processes? Describe the operation of a semaphore. What is the difference between a counting semaphore and a binary

More information

Lecture #10: Synchronization wrap up

Lecture #10: Synchronization wrap up Lecture #10: Synchronization wrap up Review -- 1 min Monitor = lock + condition variables Mesa v. Hoare semantics Advice/Summary Fall 2001 midterm: Every program with incorrect semantic behavior violated

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

Lecture 11: More on invariants and textual reasoning - examples. K. V. S. Prasad Dept of Computer Science Chalmers University Friday 30 Sep 2016

Lecture 11: More on invariants and textual reasoning - examples. K. V. S. Prasad Dept of Computer Science Chalmers University Friday 30 Sep 2016 Lecture 11: More on invariants and textual reasoning - examples K. V. S. Prasad Dept of Computer Science Chalmers University Friday 30 Sep 2016 New GU student reps please see me ABOU ZIDAN NASHWAN gusabouzna@student.gu.se

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

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

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,

More information

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

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

More information

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

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

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

CS3502 OPERATING SYSTEMS

CS3502 OPERATING SYSTEMS CS3502 OPERATING SYSTEMS Spring 2018 Synchronization Chapter 6 Synchronization The coordination of the activities of the processes Processes interfere with each other Processes compete for resources Processes

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

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

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:

More information

Process Synchronization

Process Synchronization CS307 Process Synchronization Fan Wu Department of Computer Science and Engineering Shanghai Jiao Tong University Spring 2018 Background Concurrent access to shared data may result in data inconsistency

More information

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

Operating Systems. Synchronization, part 3 Monitors, classical sync. problems Operating Systems Synchronization, part 3 Monitors, classical sync. problems 1 Monitor Monitor a synchronization primitive A monitor is a collection of procedures, variables and data structures, grouped

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

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

Process Synchronization

Process Synchronization Process Synchronization Part II, Modified by M.Rebaudengo - 2013 Silberschatz, Galvin and Gagne 2009 Classical Problems of Synchronization Consumer/Producer with Bounded-Buffer Problem s and s Problem

More information

Semaphores. Derived Inference Rules. (R g>0) Q g (g 1) {R} V (g) {Q} R Q g (g+1) V (s), hs := 1; i

Semaphores. Derived Inference Rules. (R g>0) Q g (g 1) {R} V (g) {Q} R Q g (g+1) V (s), hs := 1; i Semaphores Derived Inference Rules A shared integer variable, s, initialized to i, and manipulated only by two operations: declare: sem s := i # i 0.Default is i =0. pass (proberen): P (s), hawait(s >0)

More information

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

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

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

Threads. Concurrency. What it is. Lecture Notes Week 2. Figure 1: Multi-Threading. Figure 2: Multi-Threading Threads Figure 1: Multi-Threading Figure 2: Multi-Threading Concurrency What it is 1. Two or more threads of control access a shared resource. Scheduler operation must be taken into account fetch-decode-execute-check

More information

Deadlocks. Frédéric Haziza Spring Department of Computer Systems Uppsala University

Deadlocks. Frédéric Haziza Spring Department of Computer Systems Uppsala University Deadlocks Frédéric Haziza Department of Computer Systems Uppsala University Spring 2008 Outline 1 Quick recall on Synchronisation 2 Characterizing Deadlocks 3 Handling Deadlocks 2 OSKomp

More information

CS510 Operating System Foundations. Jonathan Walpole

CS510 Operating System Foundations. Jonathan Walpole CS510 Operating System Foundations Jonathan Walpole Monitors 2 Programming Complexity There are many ways to introduce bugs using locks and semaphores - forget to lock somewhere in the program - forget

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

Process Synchronization

Process Synchronization TDDI04 Concurrent Programming, Operating Systems, and Real-time Operating Systems Process Synchronization [SGG7] Chapter 6 Copyright Notice: The lecture notes are mainly based on Silberschatz s, Galvin

More information

Reminder from last time

Reminder from last time Concurrent systems Lecture 3: CCR, monitors, and concurrency in practice DrRobert N. M. Watson 1 Reminder from last time Implementing mutual exclusion: hardware support for atomicity and inter-processor

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

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

Synchronization 1. Synchronization

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:

More information