Operating Systems Semaphores II

Slides:



Advertisements
Similar presentations
– R 7 :: 1 – 0024 Spring 2010 Parallel Programming 0024 Recitation Week 7 Spring Semester 2010.
Advertisements

1 Chapter 5 Concurrency: Mutual Exclusion and Synchronization Principals of Concurrency Mutual Exclusion: Hardware Support Semaphores Readers/Writers Problem.
Ch 7 B.
Prepared By Sarath S Menon S6 CSE.  Imagine a scenario in which there exists two Distinct processes both operating on a single shared data area.  One.
Ch. 7 Process Synchronization (1/2) I Background F Producer - Consumer process :  Compiler, Assembler, Loader, · · · · · · F Bounded buffer.
Chapter 6 Process Synchronization Bernard Chen Spring 2007.
Chapter 6: Process Synchronization
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
EEE 435 Principles of Operating Systems Interprocess Communication Pt II (Modern Operating Systems 2.3)
Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores.
1 Semaphores and Monitors: High-level Synchronization Constructs.
COSC 3407: Operating Systems Lecture 8: Semaphores, Monitors and Condition Variables.
1 CS318 Project #3 Preemptive Kernel. 2 Continuing from Project 2 Project 2 involved: Context Switch Stack Manipulation Saving State Moving between threads,
Semaphores. Announcements No CS 415 Section this Friday Tom Roeder will hold office hours Homework 2 is due today.
Synchronization Principles. Race Conditions Race Conditions: An Example spooler directory out in 4 7 somefile.txt list.c scores.txt Process.
Semaphores, mutexes and condition variables. semaphores Two types – Binary – 0 or 1 – Counting 0 to n Wait – decrements > 0 forces a wait Post or signal.
Monitors CSCI 444/544 Operating Systems Fall 2008.
Semaphores CSCI 444/544 Operating Systems Fall 2008.
Race Conditions CS550 Operating Systems. Review So far, we have discussed Processes and Threads and talked about multithreading and MPI processes by example.
A. Frank - P. Weisberg Operating Systems Introduction to Cooperating Processes.
CS444/CS544 Operating Systems Classic Synchronization Problems 2/26/2007 Prof. Searleman
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Adopted from and based on Textbook: Operating System Concepts – 8th Edition, by Silberschatz, Galvin and Gagne Updated and Modified by Dr. Abdullah Basuhail,
Discussion Week 3 TA: Kyle Dewey. Overview Concurrency overview Synchronization primitives Semaphores Locks Conditions Project #1.
Pthread (continue) General pthread program structure –Encapsulate parallel parts (can be almost the whole program) in functions. –Use function arguments.
Semaphores. Readings r Silbershatz: Chapter 6 Mutual Exclusion in Critical Sections.
CS510 Concurrent Systems Introduction to Concurrency.
Semaphores and Bounded Buffer Andy Wang Operating Systems COP 4610 / CGS 5765.
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
Semaphores and Bounded Buffer. Semaphores  Semaphore is a type of generalized lock –Defined by Dijkstra in the last 60s –Main synchronization primitives.
4061 Session 21 (4/3). Today Thread Synchronization –Condition Variables –Monitors –Read-Write Locks.
1 Interprocess Communication (IPC) - Outline Problem: Race condition Solution: Mutual exclusion –Disabling interrupts; –Lock variables; –Strict alternation.
1 CMSC421: Principles of Operating Systems Nilanjan Banerjee Principles of Operating Systems Acknowledgments: Some of the slides are adapted from Prof.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
CIS Operating Systems Synchronization Professor Qiang Zeng Fall 2015.
COSC 3407: Operating Systems Lecture 9: Readers-Writers and Language Support for Synchronization.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
Operating Systems COMP 4850/CISG 5550 Interprocess Communication, Part II Dr. James Money.
CS 153 Design of Operating Systems Winter 2016 Lecture 7: Synchronization.
CSCI1600: Embedded and Real Time Software Lecture 17: Concurrent Programming Steven Reiss, Fall 2015.
CS510 Concurrent Systems Jonathan Walpole. Introduction to Concurrency.
1 5-High-Performance Embedded Systems using Concurrent Process (cont.)
Process Synchronization. Objectives To introduce the critical-section problem, whose solutions can be used to ensure the consistency of shared data To.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Chapter 6: Process Synchronization.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
CS162 Section 2. True/False A thread needs to own a semaphore, meaning the thread has called semaphore.P(), before it can call semaphore.V() False: Any.
pThread synchronization
CS 311/350/550 Semaphores. Semaphores – General Idea Allows two or more concurrent threads to coordinate through signaling/waiting Has four main operations.
CS703 - Advanced Operating Systems
CS703 – Advanced Operating Systems
Background on the need for Synchronization
Monitors, Condition Variables, and Readers-Writers
Thread synchronization
Lecture 13: Producer-Consumer and Semaphores
Process Synchronization
CSCI1600: Embedded and Real Time Software
CSE 451: Operating Systems Autumn Lecture 8 Semaphores and Monitors
CSE 451: Operating Systems Autumn Lecture 7 Semaphores and Monitors
Thread Synchronization including Mutual Exclusion
Lecture 13: Producer-Consumer and Semaphores
CSE 451: Operating Systems Winter Module 7 Semaphores and Monitors
CSE 153 Design of Operating Systems Winter 19
Chapter 7: Synchronization Examples
CSE 153 Design of Operating Systems Winter 2019
CS333 Intro to Operating Systems
CSCI1600: Embedded and Real Time Software
EECE.4810/EECE.5730 Operating Systems
Don Porter Portions courtesy Emmett Witchel
Review The Critical Section problem Peterson’s Algorithm
Presentation transcript:

Operating Systems Semaphores II

Producer/Consumer Problem Consumer must wait for producer to fill buffers, if none full (scheduling constraint) Producer must wait for consumer to empty buffers, if all full Only one thread can manipulate buffer queue at a time (mutual exclusion) Use a separate semaphore for each constraint

P() is a Generalization of Sleep() int BUFFER_SIZE = 100; int count = 0;  void producer(void) { int item; while(TRUE) { produce_item(&item); if(count == BUFFER_SIZE) sleep (); enter_item(item); count++; if(count == 1) wakeup(consumer); }}  void consumer(void) { int item; if(count == 0) remove_item(&item); count--; if(count == BUFFER_SIZE - 1) wakeup(producer); consume_item(&item); }} P() is a Generalization of Sleep() Mutual Exclusion Scheduling Constraint 1 Scheduling Constraint 2 V() is a Generalization of Wakeup()

P() is a Generalization of Sleep() int BUFFER_SIZE = 100; int count = 0;  void producer(void) { int item; while(TRUE) { produce_item(&item); if(count == BUFFER_SIZE) sleep (); enter_item(item); if(count == 1) wakeup(consumer); }}  void consumer(void) { int item; if(count == 0) remove_item(&item); if(count == BUFFER_SIZE - 1) wakeup(producer); consume_item(&item); }} P() is a Generalization of Sleep() Mutual Exclusion Sleep if buffer full Get Exclusive Access of Queue Leave Exclusive Access of Queue Wake up if first item in buffer Scheduling Constraint 1 Scheduling Constraint 2 Sleep if buffer empty V() is a Generalization of Wakeup() Get Exclusive Access of Queue Leave Exclusive Access of Queue Wake up if space in buffer

Get Exclusive Access of Queue int BUFFER_SIZE = 100; int count = 0;  void producer(void) { int item; while(TRUE) { produce_item(&item); empty->P(); CountMutex->P(); enter_item(item); CountMutex->V(); full->V(); }}  void consumer(void) { int item; full->P(); remove_item(&item); empty->V(); consume_item(&item); }} Semaphore Empty(BUFFER_SIZE); Semaphore full(0); Semaphore CountMutex(1); Mutual Exclusion Sleep if buffer full Get Exclusive Access of Queue Leave Exclusive Access of Queue Wake up if first item in buffer Producer/Consumer Problem solved with Semaphores Scheduling Constraint 1 Scheduling Constraint 2 Sleep if buffer empty Get Exclusive Access of Queue Leave Exclusive Access of Queue Wake up if space in buffer

Semaphore API #include <semaphore.h> How to declare semaphore? sem_t S; Initialization… sem_init(&S,0,1); Decrement ( P()) sem_wait(&S); Increment ( V() ) sem_post(&S); Max Value

Example - Ping Pong… Suppose we have two threads A and B A and B are to repeatedly print out ping and pong, respectively We want to execute them in an alternating order An alternating execution would force A and B to print out in the order of ping pong ping pong ping pong Write the pseudocode of the thread A and B How can this be solved with and without semaphores

Example - Threads A Thread creates 5 Threads. Thread 1 is created first, Thread 2 is created second, Thread 3 is created third and so on. Assume FIFO to be the scheduling policy. Each thread prints the sequence number of its creation. Write the code that will print exactly the following: I am Thread 5, I was created at number 5 I am Thread 3, I was created at number 3 I am Thread 4, I was created at number 4 I am Thread 1, I was created at number 1 I am Thread 2, I was created at number 2

Example … A thread may delay its execution by calling a function Void Delay(int second) The thread itself is blocked (no busy waiting by this thread) Wakesup roughly after second Hint I: A new thread is spawned whenever delay is called Hint II: Loops for delay?

What will happen if we swap int BUFFER_SIZE = 100; int count = 0;  void producer(void) { int item; while(TRUE) { produce_item(&item); empty->P(); CountMutex->P(); enter_item(item); CountMutex->V(); full->V(); }}  void consumer(void) { int item; full->P(); remove_item(&item); empty->V(); consume_item(&item); }} Semaphore Empty(BUFFER_SIZE); Semaphore full(0); Semaphore CountMutex(1); What will happen if we swap empty->P(); CountMutex->P();

DEADLOCK Suppose the buffer is full Where is the producer??? int BUFFER_SIZE = 100; int count = 0;  void producer(void) { int item; while(TRUE) { produce_item(&item); CountMutex->P(); empty->P(); enter_item(item); CountMutex->V(); full->V(); }}  void consumer(void) { int item; full->P(); remove_item(&item); empty->V(); consume_item(&item); }} Semaphore Empty(BUFFER_SIZE); Semaphore full(0); Semaphore CountMutex(1); Suppose the buffer is full Where is the producer??? Where is the consumer??? DEADLOCK

Solution One has to be really careful while working with the Semaphores Problem with semaphores: Used for both mutex and scheduling constraints. This makes the code hard to read, and hard to get right. Monitor: A higher level synchronization primitive Separate these 2 concepts: use locks for mutual exclusion condition variables for scheduling constraints.

Monitor A Monitor consists of A lock Zero or more condition variables For managing concurrent access to shared data Only one process can be active in the monitor at a time Acquire the lock on entry and Release the lock before returning. With condition variables, the module methods may wait and signal on multiple independent conditions.

Locks: A simple example AddToQueue() { lock.Acquire(); // lock before using shared data put item on queue; // ok to access shared data lock.Release(); // unlock after done with shared data } RemoveFromQueue() { if something on queue // ok to access shared data remove it; return item; “Roughly Equivalent” to a semaphore with value 1 Restriction that the thread that “locks” must be the one that unlocks it.

A simple example How do we change RemoveFromQueue() to wait until something is on the queue? Logically, want to go to sleep inside of critical section But if hold lock when go to sleep? other threads won't be able to get in to add things to the queue And then wake up the sleeping thread

Condition Variables: Sleep inside critical section, by atomically releasing lock at same time we go to sleep Condition variable: A queue of threads Waiting for something inside a critical section.

Condition Variables: Support three operations Wait() release lock, go to sleep, re-acquire lock Releasing lock and going to sleep is atomic Signal() wake up a waiter, if any Broadcast() wake up all waiters Rule: must hold lock when doing condition variable operations.

A simple example AddToQueue() { lock.Acquire(); // lock before using shared // data put item on queue; // ok to access shared data condition.signal(); lock.Release(); // unlock after done with // shared data } RemoveFromQueue() { lock.Acquire(); while nothing on queue condition.wait(&lock);// release lock; go // to sleep; // re-acquire lock remove item from queue; lock.Release(); return item;}

How is a conditional variable different from Semaphore? What if thread calls V() and no one is waiting? Increment – Wakeup is saved. What if thread later does calls P()? Decrement and continue – Wakeup is used. P + V are commutative Result is the same no matter what order they occur. What if thread signals and no one is waiting? Nothing Happens – No Wakeups are saved. What if thread later waits? Thread waits.

How is a conditional variable different from Semaphore? Conditional Variables are not counters Just unblock a thread if one is blocked on the conditional variable No counter incremented/decremented Just like Sleep/Wakeup except that this is atomic That's why they must be accessed in a critical section Before waiting, must check the state variables.

Producer/Consumer Problem with Monitor Constraints 1. Producers can produce if buffer not full Condition: okToProduce 2. Consumers can consume if buffer not empty Condition: okToConsume 3. Only one thread manipulates state variables at a time.

int empty = BUFFER_SIZE;   void producer(void) { int item; while(TRUE) { produce_item(&item); mutex->lock(); if(empty < = 0) okToProduce->Wait(&mutex); enter_item(item); empty--; okToConsume->Signal(); mutex->unlock();}}  void consumer(void) { int item; if(empty >= BUFFER_SIZE) okToConsume->Wait(&mutex); remove_item(&item); empty++; okToProduce->Signal(); mutex->unlock(); consume_item(&item);}}