Download presentation
Presentation is loading. Please wait.
1
Chapter 9: High-Level Synchronization
Prof. Steven A. Demurjian, Sr. † Computer Science & Engineering Department The University of Connecticut 191 Auditorium Road, Box U-155 Storrs, CT (860) † These slides have been modified from a set of originals by Dr. Gary Nutt.
2
Purpose of this Chapter
Semaphores as Presented in Chapter 8, Provide a Solution Venue for Limited Domain of Problems Other Available Synchronization Primitives AND Synchronization (Simultaneous P & V) Event Handling Monitors: ADTs for Synchronization All Techniques Offer Primitives for Software Engineers OS/Programming Level Solutions Less “Rigorous” Approach is IPC Inter-process Communication Pipes, Mailboxes, Shared Memory, etc.
3
Recall: Process Manager Overview
Abstract Computing Environment Synchronization Process Description File Manager Protection Deadlock Process Manager Device Manager Memory Manager Resource Manager Resource Manager Scheduler Resource Manager Devices Memory CPU Other H/W
4
Dining Philosophers Philosophers Think and Ignore Food
When They Want to Eat, Need Two Forks Pick Up One and Then Another How Do We Prevent Two Philosophers Holding Same Fork at Same Time? What is a Synchronization Scheme for the Problem? while(TRUE) { think(); eat(); }
5
Dining Philosophers Is Semaphore Solution Correct?
philosopher(int i) { while(TRUE) { // Think // Eat P(fork[i]); P(fork[(i+1) mod 5]); eat(); V(fork[(i+1) mod 5]); V(fork[i]); } semaphore fork[5]=(1,1,1,1,1); fork(philosopher, 1, 0); fork(philosopher, 1, 1); fork(philosopher, 1, 2); fork(philosopher, 1, 3); fork(philosopher, 1, 4);
6
Dining Philosophers A Correct Semaphore Solution
philosopher(int i) { while(TRUE) { // Think // Eat j = i % 2; P(fork[(i+j) mod 5]); P(fork[(i+1-j) mod 5]); eat(); V(fork[(i+1-j) mod 5]); V(fork[[(i+j) mod 5] ); } semaphore fork[5]=(1,1,1,1,1); fork(philosopher, 1, 0); fork(philosopher, 1, 1); fork(philosopher, 1, 2); fork(philosopher, 1, 3); fork(philosopher, 1, 4);
7
AND Synchronization Suppose Multiple Processes Need Access to Two Resources, R1 and R2 Some Processes Access R1 Some Processes Access R2, Some Processes Need Both How are Resources and Process Requests Ordered to Insure Deadlock Avoidance? Define a Simultaneous P Able to Access All Semaphores at Same Time Psimultaneous(S1, …, Sn)
8
AND Synchronization Example
semaphore mutex = 1; semaphore block = 0; P.sim(int S, int R) { P(mutex); S--; R--; if((S < 0) || (R < 0)) { V(mutex); P(block); } else V.sim(int S, int R) { P(mutex); S++; R++; if(((S >= 0) && (R >= 0)) && ((S == 0) || (R == 0))) V(block); V(mutex); }
9
Dining Philosophers Problem
philosopher(int i) { while(TRUE) { // Think // Eat Psimultaneous(fork[i], fork [(i+1) mod 5]); eat(); Vsimultaneous(fork[i], fork [(i+1) mod 5]); } semaphore fork[5] = (1,1,1,1,1); fork(philosopher, 1, 0); fork(philosopher, 1, 1); fork(philosopher, 1, 2); fork(philosopher, 1, 3); fork(philosopher, 1, 4);
10
Events Denote Many Different Things in Each OS
Used Throughout an OS to Trap Keyboard Input and Mouse Action/Location GUI: Event Driven Based on Input (KB, M) Processes Can Wait on an Event Until Another Process Signals the Event GUI Can Wait Until State of Input (KB, M,etc.) Dictates Next “Operation” to Invoke Processes are Self-Blocking During Wait Event Handling is Active, Since Process Takes Responsibility for Blocking and Reawakening
11
Events Events Tracked via Event Descriptor (“Event Control Block”) and wait and signal Operations Active Approach (Self Interrupts) Multiple Processes Can Wait on an Event Exactly One Process is Unblocked When a Signal Occurs A Signal With No Waiting Process is Ignored Passive Approach Waiting Processes Responsible for Detecting Signal May Have a Queue Function that Returns the Number of Processes Waiting on the Event
12
Example class Event { . . . public: void signal(); void wait()
int queue(); } shared Event topOfHour; . . . // Wait until the top of the hour before proceding topOfHour.wait(); // It’s the top of the hour ... shared Event topOfHour; . . . while(TRUE) if(isTopOfHour()) while(topOfHour.queue() > 0) topOfHour.signal(); }
13
Exception Handling at Programming Level!!
UNIX Signals A UNIX Signal Corresponds to an Event Raised by One Process (or Hardware) to Call Another Process’s Attention to an Event Caught (or Ignored) by the Subject Process Justification for Including Signals Was for the OS to Inform a User Process of an Event User Pressed Delete Key Program Tried to Divide by Zero Attempt to Write to a Nonexistent Pipe Etc. What are Signals Similar to? Exception Handling at Programming Level!!
14
More on Signals Each Version of UNIX Has a Fixed Set of Signals (Linux Has 31 of Them) signal.h Defines the Signals in the OS Application Programs Can Use SIGUSR1 & SIGUSR2 for Arbitrary Signaling Raise a Signal With kill(pid, signal) Process Can Let Default Handler Catch the Signal, Catch the Signal With Own Code, or Cause the Signal to Be Ignored
15
Signals in Sun Unix #define SIGHUP 1 /* hangup */
#define SIGINT 2 /* interrupt (rubout) */ #define SIGQUIT 3 /* quit (ASCII FS) */ #define SIGILL 4 /* illegal instruction (not reset when caught)*/ #define SIGTRAP 5 /* trace trap (not reset when caught) */ #define SIGIOT 6 /* IOT instruction */ #define SIGABRT 6 /* used by abort, replace SIGIOT in the future*/ #define SIGEMT 7 /* EMT instruction */ #define SIGFPE 8 /* floating point exception */ #define SIGKILL 9 /* kill (cannot be caught or ignored) */ #define SIGBUS 10 /* bus error */ #define SIGSEGV 11 /* segmentation violation */ #define SIGSYS 12 /* bad argument to system call */ #define SIGPIPE 13 /* write on a pipe with no one to read it */ #define SIGALRM 14 /* alarm clock */ #define SIGTERM 15 /* software termination signal from kill */ #define SIGUSR1 16 /* user defined signal 1 */ #define SIGUSR2 17 /* user defined signal 2 */
16
Signals in Sun Unix #define SIGCLD 18 /* child status change */
#define SIGCHLD 18 /* child status change alias (POSIX) */ #define SIGPWR 19 /* power-fail restart */ #define SIGWINCH 20 /* window size change */ #define SIGURG 21 /* urgent socket condition */ #define SIGPOLL 22 /* pollable event occured */ #define SIGIO SIGPOLL /* socket I/O possible (SIGPOLL alias) */ #define SIGSTOP 23 /* stop (cannot be caught or ignored) */ #define SIGTSTP 24 /* user stop requested from tty */ #define SIGCONT 25 /* stopped process has been continued */ #define SIGTTIN 26 /* background tty read attempted */ #define SIGTTOU 27 /* background tty write attempted */ #define SIGVTALRM 28 /* virtual timer expired */ #define SIGPROF 29 /* profiling timer expired */ #define SIGXCPU 30 /* exceeded cpu limit */ #define SIGXFSZ 31 /* exceeded file size limit */ #define SIGWAITING 32 /* process's lwps are blocked */ #define SIGLWP 33 /* special signal used by thread library */
17
More on Signals (Continued)
OS Signal System Call To Ignore: Signal(sig#, SIG_IGN) To Reinstate Default: Signal(sig#, SIG_DFL) To Catch: Signal(sig#, Myhandler) Provides a Facility for Writing Your Own Event Handlers in the Style of Interrupt Handlers
18
See Detailed Code for Signaling in Unix in Figure 9.4
Signal Handling /* code for process p . . . signal(SIG#, sig_hndlr); /* ARBITRARY CODE */ void sig_hndlr(...) { /* ARBITRARY CODE */ } An Executing Process, q Raise “SIG#” for “p” sig_hndlr runs in p’s address space q is Blocked q Resumes Execution See Detailed Code for Signaling in Unix in Figure 9.4
19
Event Objects in NT An Event Object Announces Occurrence of “Something” in One Thread that Needs to be Known in Other Threads Visibility of Event via: Event Signal Seen by only one Thread Event Signal may be Seen by Multiple Threads Thus, One Event Object May Signal One Thread One Event Object May Signal Many Threads Many Event Object May Signal Same Thread
20
NT Events Signaled Implicitly Manually Callbacks
Thread Signaled Implicitly Manually Callbacks WaitForSingleObject(foo, time); Signaled/Not Signaled Flag Kernel object Waitable timer
21
NT Events Thread Thread Thread WaitForSingleObject(foo, time);
22
NT Events Thread WaitForMultipleObjects(foo, time);
23
Events and Event Handling in Java
Events and Event Handling in Java are Integral to Correct Operation of GUIs using AWT Event Handling in Java is … Detecting and Processing User Inputs Events Include Keyboard, Mouse Clicks, etc. Events Such as Value and Screen Appearance Changes also Possible Event Handling Code Critical for Useful Applications Solutions Must be Structured Around Specific Event Processing Model of Computation See
24
The Java 1.1 Event Model Contrast with MS-Windows and X
Event Model was Able to Handle Flood of Events Recorded from Different Places Ability to Process Flood of Events Events Processed Through a Giant ‘Switch’ Statement Advantage/Disadvantage Easy to Implement/Hard to Evolve Use of a Switch Statement Implies a Decidedly Non-OO Design What is Another Alternative?
25
The Java 1.1 Event Model Contrast with Microsoft Foundation Classes Programming Model or Motif Programming Model Each Component Must Be Over-Ridden to Make It Do What You Want It to Do Something Similar to the Older Java 1.0 Inheritance Event Model This Approach is More Object-Oriented, But Involves a Great Deal of Work Inheritance Model Can Limit Flexibility and Power, since Java Doesn’t Support Multiple Inheritance Recall a Java Class May Implement Multiple Interfaces but only Extend a Single Class
26
The Java 1.1 Event Model In the New Java 1.1 Delegation Event Model
More Specificity in Controlling Events Based on Individual Components A Component Can Defined as Follows Identify Which Events are to be Handled by Each Component at Design/Implementation Level At Runtime, Component Knows Which Object or Objects Should Be Notified When the Component Generates a Particular Type of Event If a Component is Not Interested in an Event Type Then Events of That Type Will Not Be Propagated That is, Component can Ignore Certain Events
27
The Java 1.1 Event Model (According to Sun)
Simple and Easy to Learn Support a Clean Separation Between Application and GUI Code Flexible Enough to Enable Varied Application Models for Event Flow and Propagation For Visual Tool Builders, Enable Run-time Discovery of Both Events That a Component Generates as Well as the Events It May Observe Support Backward Binary Compatibility With the Old Model (Java 1.0 Inheritance Event Model) Facilitate the Creation of Robust Event Handling Code Which is Less Error-prone (Strong Compile-time Checking)
28
Java’s 1.1 Delegation Event Model Event Listener and Event Source
Event Listener: Any Object Interested in Receiving Messages (or Events) Entity That Desires Notification When an Event Happens Receives the Specific Eventobject Subclass as a Parameter Event Source: Any Object That Generates These Messages (or Events) Defines When and Where an Event Will Happen Hireevent and Hirelistener are Required for an Event Source to Function Sends Notification to Registered Classes When the Event Happens
29
Java 1.1 Delegation Event Model
30
Event Classes
31
Types of Events ActionEvent Generated by Component Activation
AdjustmentEvent Generated by Adjustment of Adjustable Components Such as Scroll Bars ContainerEvent Generated When Components are Added to or Removed From a Container FocusEvent Generated When a Component Receives Input Focus ItemEvent Generated When an Item is Selected From a List, Choice or Check Box KeyEvent Generated by Keyboard Activity MouseEvent Generated by Mouse Activity PaintEvent Generated When a Component is Painted TextEvent Generated When a Text Component is Modified WindowEvent Generated by Window Activity Like Minimizing or Maximizing
32
The 1.1 Delegation Event Model
Event Source Object Maintains Listeners List Who are Interested in Receiving Events that It Produces Event Source Object Provides Methods That Allow the Listeners to Add Themselves ( ‘Register’ ) to This List of ‘Interested’ Objects Remove Themselves From This List of ‘Interested’ Objects. Event Source Object Notifies All the Listeners That the Event Has Occurred When Event Source Object Generates an Event When User Input Event Occurs on the Event Source Object
33
Event Object Interactions
An Event Source Object Notifies an Event Listener Object by Invoking a Method on Listener Object Passing Listener Object an EventObject In Order for the Event Source Object to Invoke a Method on a Listener All Listeners Must Implement the Required Method Guaranteed by Requiring All Event Listeners for a Particular Type of Event Implement a Corresponding Interface
34
Example: Event for Employee’s Hire Date
public class HireEvent extends EventObject { private long hireDate; public HireEvent (Object source) { super (source); hireDate = System.currentTimeMillis(); } public HireEvent (Object source, long hired) { hireDate = hired; public long getHireDate () { return hireDate;
35
Event Listeners Event Listeners are Objects That Are Responsible for Handling a Particular Task of a Component Event Listener Typically Implements a Java Interface That Contains Event-Handling Code for a Particular Component Standard Pattern for Giving Listener to Component Create a Listener Class That Implements the Corresponding Listener Interface Construct the Component Construct an Instance of the Listener Interface Call Add...Listener() on the Component, Passing in the Listener
36
The EventListener Interface
Empty Interface Acts as a Tagging Interface That All Event Listeners Must Extend Eventtypelistener Name of Listener Interface The Name for the New Hireevent Listener Would Be Hirelistener Method Names Should Describe the Event Happening Code public interface HireListener extends java.util.EventListener { public abstract void hired (HireEvent e); }
37
EventSource Interface Methods
Registration Process Method Patterns public synchronized void addListenerType(ListenerType l); removeListenerType(ListenerType l); Maintaining Eventsource Code private Vector hireListeners = new Vector(); addHireListener(HireListener l) { hireListeners.addElement (l); } removeHireListener (HireListener l) { hireListeners.removeElement (l);
38
EventSource: Hiring Example
protected void notifyHired () { vector l; // Create Event HireEvent h = new HireEvent (this); // Copy listener vector so it won't change while firing synchronized (this) { l = (Vector)hireListeners.clone(); } for (int i=0;i<l.size();i++) { HireListener hl = (HireListener)l.elementAt (i); hl.hired(h);
39
Monitors Specialized Form of ADT Encapsulates Implementation
Public Interface (Types & Functions) Only One Process Can Be Executing (Invoking a Method) in the ADT at a Time One Shared Instance of ADT! monitor anADT { semaphore mutex = 1; // Implicit . . . public: proc_i(…) { P(mutex); // Implicit <processing for proc_i>; V(mutex); // Implicit };
40
Example: Shared Balance
Consider the Shared Balance Monitor Below. Each Method (credit/debit) Define Critical Section Hence, by its Definition … Methods Disable Interrupts at Start of Call and Re-enable Interrupts at End of Call monitor sharedBalance { double balance; public: credit(double amount) {balance += amount;}; debit(double amount) {balance -= amount;}; . . . };
41
Example: Readers & Writers
monitor readerWriter_1 { int numberOfReaders = 0; int numberOfWriters = 0; boolean busy = FALSE; public: startRead() { }; finishRead() { startWrite() { finishWrite() { reader(){ while(TRUE) { . . . startRead(); finishRead(); } fork(reader, 0); fork(reader, 0): fork(writer, 0); writer(){ while(TRUE) { . . . startWrite(); finishWrite(); }
42
Example: Readers & Writers
monitor readerWriter_1 { int numberOfReaders = 0; int numberOfWriters = 0; boolean busy = FALSE; public: startRead() { while(numberOfWriters != 0) ; numberOfReaders++; }; finishRead() { numberOfReaders-; startWrite() { numberOfWriters++; while( busy || (numberOfReaders > 0) ) ; busy = TRUE; }; finishWrite() { numberOfWriters--; busy = FALSE;
43
Example: Readers & Writers
monitor readerWriter_1 { int numberOfReaders = 0; int numberOfWriters = 0; boolean busy = FALSE; public: startRead() { while(numberOfWriters != 0); numberOfReaders++; }; finishRead() { numberOfReaders--; Deadlock can Occur! startWrite() { numberOfWriters++; while( busy || (numberOfReaders > 0) ) ; busy = TRUE; }; finishWrite() { numberOfWriters--; busy = FALSE;
44
Further Monitor Execution Semantics
Recall that in P Operation for Semaphore, Wait Gives Opportunity to Interrupt Suppose Process Obtains Monitor Then, Monitor Detects a Condition for Which it Needs to Wait Since Only One Process Using Monitor at Any One Time, Other Processes Wait Forever Need Special Mechanism to Suspend Process Until Condition is Met, Then Resume Process That Makes Condition TRUE Must Exit Monitor Suspended Process Must be Able to Resume Introduce Concept of Condition Variable
45
Condition Variables Essentially an Event (As Defined Previously)
Global Condition Visible to All Methods Defined in Monitor -- Occurs Only Inside a Monitor Operations to Manipulate Condition Variable Wait: Suspend Invoking Process Until Another Executes a Signal Signal: Resume One Process If Any Are Suspended, Otherwise Do Nothing Queue: Return TRUE If There is at Least One Process Suspended on the Condition Variable Conditions Increase Complexity of Monitor Transcends Traditional Semaphore Capabilities
46
Active vs. Passive Signal
Hoare Semantics: Same as Active Semaphore p0 Executes Signal while p1 is Waiting p0 Yields the Monitor to p1 The Signal is only TRUE the Instant it Happens p0 Generates Self Interrupt for p1 Brinch Hansen (“Mesa”) Semantics: Same as Passive Semaphore p0 Executes Signal while p1 is Waiting p0 Continues to Execute When p0 exits the Monitor p1 can Receive the Signal p0 Responsible for Receiving Signal Used in the Xerox Mesa Implementation
47
Hoare vs. Mesa Semantics
Hoare semantics: . . . if(resourceNotAvailable()) resourceCondition.wait(); /* now available … continue … */ Mesa semantics: . . . while(resourceNotAvailable()) resourceCondition.wait(); /* now available … continue … */
48
Second Try at Readers & Writers
monitor readerWriter_2 { int numberOfReaders = 0; boolean busy = FALSE; condition okToRead, okToWrite; public: // startRead and finishRead used by Readers startRead() { if(busy || // busy = TRUE implies writer (okToWrite.queue()) okToRead.wait(); numberOfReaders++; okToRead.signal(); }; finishRead() { numberOfReaders--; if(numberOfReaders == 0) okToWrite.signal();
49
Second Try at Readers & Writers
// startWrite and finishWrite Used by Writers startWrite() { if((numberOfReaders != 0) || busy) okToWrite.wait(); busy = TRUE; }; finishWrite() { busy = FALSE; if(okToRead.queue()) okToRead.signal() else okToWrite.signal() Each Method is Atomic! Cannot be Interrupted!
50
Example: Synchronizing Traffic
One-Way Tunnel Can Only Use Tunnel If No Oncoming Traffic OK to Use Tunnel If Traffic is Already Flowing the Right Way Differentiate Between Northbound and Southbound Traffic Reset Light from Red to Green (and Green to Red) to Control Flow
51
Example: Synchronizing Traffic
monitor tunnel { int northbound = 0, southbound = 0; trafficSignal nbSignal = RED, sbSignal = GREEN; condition busy; public: nbArrival() { if(southbound > 0) busy.wait(); northbound++; nbSignal = GREEN; sbSignal = RED; }; sbArrival() { if(northbound > 0) busy.wait(); southbound++; nbSignal = RED; sbSignal = GREEN;
52
Ex: Synchronizing Traffic (Continued)
depart(Direction exit) ( if(exit = NORTH { northbound--; if (northbound == 0) while(busy.queue()) busy.signal(); else if (exit == SOUTH) { southbound--; if(southbound == 0) } // SOUTH if } // NORTH if }; // depart method }; tunnel monitor
53
Dining Philosophers … again ...
#define N // Set to Number of Phisophers enum status(EATING, HUNGRY, THINKING}; monitor diningPhilosophers { status state[N]; condition self[N]; test(int i) { // Private method if((state[(i-1) mod N] != EATING) && (state[i] == HUNGRY) && (state[(i+1) mod N] != EATING)) { state[i] = EATING; self[i].signal(); } }; public: diningPhilosophers(){//Initialization/Constructor for(int i = 0; i < N; i++) state[i] = THINKING;
54
Dining Philosophers … again ...
test(int i) { // Private method if((state[(i-1) mod N] != EATING) && (state[i] == HUNGRY) && (state[(i+1) mod N] != EATING)) { state[i] = EATING; self[i].signal(); } }; public: pickUpForks(int i) { state[i] = HUNGRY; test(i); if(state[i] != EATING) self[i].wait(); putDownForks(int i) { state[i] = THINKING; test((i-1) mod N); test((i+1) mod N);
55
Experience with Monitors
Danger of Deadlock With Nested Calls Monitors Were Implemented in Mesa Used Brinch Hansen Semantics Nested Monitor Calls Are, in Fact, a Problem Difficult to Get the Right Behavior With These Semantics Needed Timeouts, Aborts, Etc. Monitors Haven’t Caught On in “Real World” Currently Unavailable in Most OSs Powerful Mechanism Difficult to Implement Superceded by Programmer Level Alternatives IPC Synchronization via Thread Executions
56
Interprocess Communication (IPC)
Signals, Semaphores, Etc. do not Pass Information From One Process to Another Monitors Support Information Sharing, but Only Through Shared Memory in the Monitor There May Be No Shared Memory OS Does Not Support It Processes are on Different Machines on a Network Can Use Messages to Pass Information While Synchronizing Actions Message: Formatted Block of Information Encoded by Sender, Decode by Receiver Agreement re. Format
57
Synchronization via IPC
Recall MBDS Database Controller (C) One or More Backend (BE) Database Processes Interact via Message Passing Synchronization Attained via Reliable Broadcast: C to BE and Among BE Guarantees that Messages Always Received in Specific Order Message Queues Maintained to Insure Messages Processed in Order Received MBDS Evolved from Shared Memory to Mailboxes to Pipes to TCP/IP
58
Recall Process/Messages in MBDS
Get Msg. Put Msg. Request Preparation Post Processing Directory Management Record Concurrency Control Disk I/O F15 From Other Backend E15 To Backend(s) A1 B3 C4 D6 D6,F15 E15 G21 H22 I16 J23 K12
59
MBDS Architecture Network: Ethernet for Reliable Broadcast
Database Controller Backend Database Processor Processor Host/User Broadcast Message Controls Network Traffic Guarantees Order of Transmitted Messages
60
IPC Mechanisms Must Bypass Memory Protection Mechanism for Local Copies Copy Info. Own Address Space to Msg. IPC Mechanism Copies Msg. to Receiving Processes Address Space Must Be Able to Use a Network for Remote Copies Send/Receive Bypass Memory Protection Address Space for p0 Info to be shared Message Info copy OS IPC Mechanism for p1
61
Refined IPC Mechanism: Mailbox Located within Address Space of Receiver
Spontaneous Changes to p1’s Address Space Pro: Receive Call Copy within Address Space Con: Compiler/Loader Must Allocate Space within “Executable” for Mailbox. How Much is Needed? Con: Receiver Overwrites Messages/Mailboxes Info to be shared Info copy Address Space for p0 Address Space for p1 Message Mailbox for p1 send function receive function OS Interface send(… p1, …); receive(…);
62
Refined IPC Mechanism: Mailbox Independent of Sender/Receiver
OS Manages the Mailbox Space More Secure Message System Pro: Prevents Inadvertent Destruction of Messages Con: OS Must Allocate Memory for Mailboxes Con: Mailboxes Shared for All Processes Overall: Typically Chosen Approach for OS Info to be shared Info copy Address Space for p0 for p1 Message Mailbox for p1 send function receive function OS Interface send(… p1, …); receive(…);
63
Message Protocols A Message Protocol is Agreement Between Sender and Receiver on the Format of Messages Sender Transmits a Set of Bits to Receiver How Does the Sender Know When the Receiver is Ready (or When the Receiver Obtained the Information)? How Does the Receiver Know How to Interpret the Info? Need a Protocol for Communication Standard “Envelope” for Containing the Information Standard Header: Sender ID, Receiver ID, # Bytes A Message System Specifies the Protocols
64
Potential Pitfalls with Message Protocols
Consulting Project in 1995 Client/Server Architecture Clients (16 bit or 32 bit Machines) Servers (32 bit Machines) IPC via Message Passing using C “Same” Message Passing Software in Client/Server Utilized Structures for Message Filled Structure on Server Encoded to Message Empty Structure on Client Decoded/Filled with Message What Problem did we Encounter?
65
Send and Receive Operations
Send: Message from Process A to Process B Synchronous Asynchronous Receive: Process B Gets Process A’s Message How Does Process B Wait? Similarity to Semaphores: P and V Sender is Producer - Does P Operation to Send Receiver is Consumer - Does V Operation to Receive
66
Transmit Operations Asynchronous Send:
Delivers Message to Receiver’s Mailbox Sending Process Continues Execution No Feedback on When (or If) Information Was Delivered Reliable Protocol Can Help Here MBDS Utilized Asynchronous Send Synchronous Send: Goal is to Block Sender Until Message is Received by a Process Sender Must Wait Until Message is “Received” Variant Sometimes Used in Networks: Until the Message is in the Mailbox
67
Receive Operation Blocking Receive:
Return the First Message in the Mailbox If There is No Message in Mailbox, Block the Receiver Until One Arrives Non-blocking Receive: If There is No Message in Mailbox, Return With an Indication to That Effect
68
Synchronized IPC Code for p1 Code for p2 /* signal p2 */
syncSend(…) blockReceive(…) Code for p1 Code for p2 /* signal p2 */ syncSend(message1, p2); <waiting …>; /* wait for signal from p2 */ blockReceive(msgBuff, &from); /* wait for signal from p1 */ blockReceive(msgBuff, &from); <process message>; /* signal p1 */ syncSend(message2, p1);
69
Asynchronous IPC Code for p1 Code for p2 /* signal p2 */
asyncSend(…) nonblockReceive(…) Code for p1 Code for p2 /* signal p2 */ asyncSend(message1, p2); <other processing>; /* wait for signal from p2 */ while(!nbReceive(&msg, &from)); /* test for signal from p1 */ if(nbReceive(&msg, &from)) { <process message>; asyncSend(message2, p1); }else <other processing>; }
70
UNIX Pipes Major IPC Mechanism in Unix (“|”)
Asynchronous Send and Blocking Receive (Default) Write to One End of Pipe and Read from Other End of Pipe Info to be shared Info copy Address Space for p1 pipe for p1 and p2 write function read function System Call Interface write(pipe[1], …); read(pipe[0]);
71
UNIX Pipes (continued)
Pipe Interface Intentionally Mirrors File Interface Analog of Open is to Create the Pipe File Read/Write System Calls are Used to Send/Receive Information on the Pipe What is Going on Here? Kernel Creates a FIFO Buffer When Pipe is Requested Pipe has Two File Identifiers pipeID[0] File Pointer For Read End of Pipe pipeID[1] File Pointer for Write End of Pipe Processes Can Read/Write into/out of Their Address Spaces from/to the Buffer Processes Just Need a Handle to the Buffer
72
UNIX Pipes (Continued)
File Handles Are Copied on Fork … So Are Pipe Handles int pipeID[2]; . . . pipe(pipeID); if(fork() == 0) { /* the child */ read(pipeID[0], childBuf, len); <process the message>; } else { /* the parent */ write(pipeID[1], msgToChild, len); }
73
UNIX Pipes (Continued)
Normal Write is an Asynchronous Operation that Notifies of Write Errors Normal Read is a Blocking Read Read Operation Can Be Nonblocking #include <sys/ioctl.h> . . . int pipeID[2]; pipe(pipeID); ioctl(pipeID[0], FIONBIO, &on); read(pipeID[0], buffer, len); if(errno != EWOULDBLOCK) { /* no data */ } else { /* have data */
74
Concluding Remarks/Looking Ahead
Advanced Synchronization Principles Signal and Monitors: Minimal Shared State IPC via Message Passing, Pipes, etc. Ability to Send/Receive Messages Communicate Information Synchronize Actions Across Computers Interesting Exercise 4 in Section 9.6 Sleepy Barber Problem via Monitors What about Soda-Jerk Problem via Monitors? Looking Ahead to … Deadlock (Chapter 10) Memory Management (Chapters 11 & 12)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.