SlideShare a Scribd company logo
1 of 30
Interprocess
Communication
CS4532 Concurrent Programming
Dilum Bandara
Dilum.Bandara@uom.lk
Slides extended from “Modern Operating Systems” by A. S. Tanenbaum
and “The Little Book of Semaphores” by Allen B. Downey
Outline
 Issues
 How 1 process pass data to another
 Making sure processes don’t get into each other’s
way while engaged in critical activity
 Proper sequencing when dependencies are present
 Solutions
 Semaphores
 Mutexes
 Monitors
 Message Passing
 Barriers
2
Race Conditions
 2 processes want to access shared memory at same time
 Race conditions – when 2 or more processes read/write a
shared resource & final result depends on who runs correctly
 Solution – mutual exclusion 3
Printer
daemon
Critical Regions
 Part of a program where a shared resource is
accessed
 Make sure no 2 processes are in critical region
at same time  avoid race condition
 4 conditions to provide mutual exclusion
1. No 2 processes simultaneously in critical region
2. No assumptions made about speeds or no of CPUs
3. No process running outside its critical region may
block another process
4. No process must wait forever to enter its critical
region
4
Critical Regions (Cont.)
Mutual exclusion using critical regions
5
Supporting Mutual Exclusion
 Disabling interrupts
 No preemption
 What if a process never enable interrupts?
 Strict alternation
 Strict turns
 Lock variables
 Single, shared variable
 Reading & writing into lock is not atomic
6
Mutual Exclusion with Busy Waiting
 Proposed solution to critical region problem
 (a) Process 0, (b) Process 1
 Problems?
7
Mutual Exclusion with Busy Waiting (Cont.)
Peterson's solution for achieving mutual exclusion 8
Mutual Exclusion with Busy Waiting (Cont.)
 TSL – Test & set lock
 Entering & leaving a critical region using TSL
assembly instruction
9
Issues with Busy Waiting
 Waste CPU time
 Unexpected effects
 Process h with high priority & process l with low
priority
 When h is busy waiting l will never get a chance to
leave critical region
 Solution
 Sleep & wakeup
10
Sleep & Wakeup
Producer-consumer problem with fatal race condition
11
Not atomic
Semaphores
 Internal Counter capable of providing mutual
exclusion & synchronization
 Counter can go Up & Down
 If down() when counter is zero, thread blocks
 When up() counter increases & if there are waiting
threads, one of them is released/wakeup
12
Semaphores (Cont.)
 Integer variable to count no of wakeups saved
for future use
 0 – no wakeups pending
 1+ – 1 or more wakeups pending
 Operations
 down()
 If count > 0, decrement value & continue – atomic
 If count = 0, sleep – atomic
 up()
 If count >= 0 and no one sleeping, increment value &
continue – atomic
 If count == 0, wakeup one of the sleeping threads – atomic
13
Semaphore Implementation If
Count Can Be Negative
 down()
 Decrement value
 If count >= 0 continue
 Else sleep
 up()
 Increment value
 If count > 0 continue
 Else wakeup one of the sleeping threads
14
Properties of Semaphores
 Semaphores can be initialized to any integer
 foo = Semaphore(100)
 Binary semaphore
 Initialized to 0 & used by 2+ processors to ensure only 1 can enter
critical region
 After that only allowed operations are up() & down()
 foo.up() = foo.signal()
 foo.down() = foo.wait()
 Usually can’t read current value of a semaphore
 When down() is called, if counter = 0, thread is blocked &
can’t continue until another thread calls up()
 When up() is called, if there are other threads waiting, 1 of
them gets unblocked 15
Why Semaphores?
 Impose deliberate constraints that help
programmers avoid errors
 Solutions using semaphores are often clean &
organized
 Make it easy to demonstrate their correctness
 Can be implemented efficiently on many
systems
 Solutions that use semaphores are portable & usually
efficient
16
Example – Print A before B
Lock l
Thread 1
Print A
l.unlock();
Thread 2
l.lock();
l.lock();
Print B
17
• What if only Thread 1 get executed first?
• Fix above solution with Semaphores
Fixed Solution With Semaphores
Semaphore s = new S(1)
Thread 1
Print A
s.up();
Thread 2
s.down();
s.down();
Print B
18
• Is there a better way?
Exercise
Lock lock = new Lock();
Thread1{
Print A
lock.unlock()
}
Thread2{
lock.lock()
Print B
}
 Provide 2 possible outcome of the above program
 How can you use semaphore instead of Locks, such that
program will print A & B in order
19
Mutexes
 When a semaphore’s ability to count is not needed
 To enforce mutual exclusion
 Implementation of mutex_lock & mutex_unlock
20
Producer-Consumer Problem Using
Semaphores
21
Monitors
 Lock & Semaphores to work, code should be
well behaved
 But we often forget …
 Monitors are the solution
 Ensure exclusive access to resources, & for
synchronizing & communicating among tasks
 Natural, elegant, & efficient mechanisms
 Especially for systems with shared memory
22
Monitors (Cont.)
 Collection of variables, data structures, &
procedures (entry routines) to support high-level
synchronization
 Typically, monitor data can be manipulated only
through entry routines
 Only 1 task at a time can execute any entry routine
 Called active task
 Ensure exclusive access to resources, & for
synchronizing & communicating among tasks
 Natural, elegant, & efficient mechanisms
 Especially for systems with shared memory
23
Monitors (Cont.)
 Enforce mutual exclusion by
1. Locking monitor when execution of an entry routine
begins
2. Unlocking it when active task voluntarily gives up
control of the monitor
 If another task invokes an entry routine while
monitor is locked, task is blocked until monitor
becomes unlocked
 Enforced by a library or operating system
24
Monitors (Cont.)
25
Java Example
public class MyMonitor {
private final Lock lock = new ReentrantLock();
public void testA() {
lock.lock();
try {
//Some code
} finally {
lock.unlock();
}
}
public int testB() {
lock.lock();
try {
return 1;
} finally {
lock.unlock();
}
}
} 26
Advantages of Monitors
 All synchronization code is centralized in one
location
 If already implemented, users don’t need to know how
it’s implemented
 Code doesn’t depend on number of processes
 You don’t need to release something like a
mutex, so you can’t forget to do it
27
Barriers
 Use of a barrier
 Processes approaching a barrier
 All processes but 1 blocked at barrier
 Last process arrives, all are let through
 E.g., matrix iterations
28
Multiplex
 Critical section that let only N threads to enter at
a given time
 Can implement using a Semaphore initialized to N
29
Source: www.codeproject.com
Message Passing – Producer-Consumer
Problem with N Messages
30

More Related Content

Similar to Interprocess Communication

Lecture 9 - Process Synchronization.pptx
Lecture 9 - Process Synchronization.pptxLecture 9 - Process Synchronization.pptx
Lecture 9 - Process Synchronization.pptxEhteshamulIslam1
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slotsmha4
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slotsmha4
 
BIL406-Chapter-9-Synchronization and Communication in MIMD Systems.ppt
BIL406-Chapter-9-Synchronization and Communication in MIMD Systems.pptBIL406-Chapter-9-Synchronization and Communication in MIMD Systems.ppt
BIL406-Chapter-9-Synchronization and Communication in MIMD Systems.pptKadri20
 
slides8 SharedMemory.ppt
slides8 SharedMemory.pptslides8 SharedMemory.ppt
slides8 SharedMemory.pptaminnezarat
 
Process Synchronization And Deadlocks
Process Synchronization And DeadlocksProcess Synchronization And Deadlocks
Process Synchronization And Deadlockstech2click
 
A Multi-Agent System Approach to Load-Balancing and Resource Allocation for D...
A Multi-Agent System Approach to Load-Balancing and Resource Allocation for D...A Multi-Agent System Approach to Load-Balancing and Resource Allocation for D...
A Multi-Agent System Approach to Load-Balancing and Resource Allocation for D...Soumya Banerjee
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronizationlodhran-hayat
 
Concurrency: Mutual Exclusion and Synchronization
Concurrency: Mutual Exclusion and SynchronizationConcurrency: Mutual Exclusion and Synchronization
Concurrency: Mutual Exclusion and SynchronizationAnas Ebrahim
 
CS844 U1 Individual Project
CS844 U1 Individual ProjectCS844 U1 Individual Project
CS844 U1 Individual ProjectThienSi Le
 
Os solved question paper
Os solved question paperOs solved question paper
Os solved question paperAnkit Bhatnagar
 
Concurrency Control in Distributed Systems.pptx
Concurrency Control in Distributed Systems.pptxConcurrency Control in Distributed Systems.pptx
Concurrency Control in Distributed Systems.pptxMArshad35
 
Lab 1 reference manual
Lab 1 reference manualLab 1 reference manual
Lab 1 reference manualtrayyoo
 
Operating System- INTERPROCESS COMMUNICATION.docx
Operating System- INTERPROCESS COMMUNICATION.docxOperating System- INTERPROCESS COMMUNICATION.docx
Operating System- INTERPROCESS COMMUNICATION.docxminaltmv
 
Lecture 7, 8, 9 and 10 Inter Process Communication (IPC) in Operating Systems
Lecture 7, 8, 9 and 10  Inter Process Communication (IPC) in Operating SystemsLecture 7, 8, 9 and 10  Inter Process Communication (IPC) in Operating Systems
Lecture 7, 8, 9 and 10 Inter Process Communication (IPC) in Operating SystemsRushdi Shams
 

Similar to Interprocess Communication (20)

Lecture 9 - Process Synchronization.pptx
Lecture 9 - Process Synchronization.pptxLecture 9 - Process Synchronization.pptx
Lecture 9 - Process Synchronization.pptx
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
04 threads-pbl-2-slots
04 threads-pbl-2-slots04 threads-pbl-2-slots
04 threads-pbl-2-slots
 
BIL406-Chapter-9-Synchronization and Communication in MIMD Systems.ppt
BIL406-Chapter-9-Synchronization and Communication in MIMD Systems.pptBIL406-Chapter-9-Synchronization and Communication in MIMD Systems.ppt
BIL406-Chapter-9-Synchronization and Communication in MIMD Systems.ppt
 
slides8 SharedMemory.ppt
slides8 SharedMemory.pptslides8 SharedMemory.ppt
slides8 SharedMemory.ppt
 
Process Synchronization And Deadlocks
Process Synchronization And DeadlocksProcess Synchronization And Deadlocks
Process Synchronization And Deadlocks
 
A Multi-Agent System Approach to Load-Balancing and Resource Allocation for D...
A Multi-Agent System Approach to Load-Balancing and Resource Allocation for D...A Multi-Agent System Approach to Load-Balancing and Resource Allocation for D...
A Multi-Agent System Approach to Load-Balancing and Resource Allocation for D...
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
 
Concurrency: Mutual Exclusion and Synchronization
Concurrency: Mutual Exclusion and SynchronizationConcurrency: Mutual Exclusion and Synchronization
Concurrency: Mutual Exclusion and Synchronization
 
CS844 U1 Individual Project
CS844 U1 Individual ProjectCS844 U1 Individual Project
CS844 U1 Individual Project
 
Os solved question paper
Os solved question paperOs solved question paper
Os solved question paper
 
Sayeh extension(v23)
Sayeh extension(v23)Sayeh extension(v23)
Sayeh extension(v23)
 
Concurrency Control in Distributed Systems.pptx
Concurrency Control in Distributed Systems.pptxConcurrency Control in Distributed Systems.pptx
Concurrency Control in Distributed Systems.pptx
 
Ipc feb4
Ipc feb4Ipc feb4
Ipc feb4
 
Lab 1 reference manual
Lab 1 reference manualLab 1 reference manual
Lab 1 reference manual
 
Synchronization
SynchronizationSynchronization
Synchronization
 
Operating System- INTERPROCESS COMMUNICATION.docx
Operating System- INTERPROCESS COMMUNICATION.docxOperating System- INTERPROCESS COMMUNICATION.docx
Operating System- INTERPROCESS COMMUNICATION.docx
 
Os unit 3
Os unit 3Os unit 3
Os unit 3
 
CHAP4.pptx
CHAP4.pptxCHAP4.pptx
CHAP4.pptx
 
Lecture 7, 8, 9 and 10 Inter Process Communication (IPC) in Operating Systems
Lecture 7, 8, 9 and 10  Inter Process Communication (IPC) in Operating SystemsLecture 7, 8, 9 and 10  Inter Process Communication (IPC) in Operating Systems
Lecture 7, 8, 9 and 10 Inter Process Communication (IPC) in Operating Systems
 

More from Dilum Bandara

Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine LearningDilum Bandara
 
Time Series Analysis and Forecasting in Practice
Time Series Analysis and Forecasting in PracticeTime Series Analysis and Forecasting in Practice
Time Series Analysis and Forecasting in PracticeDilum Bandara
 
Introduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCAIntroduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCADilum Bandara
 
Introduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive AnalyticsIntroduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive AnalyticsDilum Bandara
 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresDilum Bandara
 
Hard to Paralelize Problems: Matrix-Vector and Matrix-Matrix
Hard to Paralelize Problems: Matrix-Vector and Matrix-MatrixHard to Paralelize Problems: Matrix-Vector and Matrix-Matrix
Hard to Paralelize Problems: Matrix-Vector and Matrix-MatrixDilum Bandara
 
Introduction to Map-Reduce Programming with Hadoop
Introduction to Map-Reduce Programming with HadoopIntroduction to Map-Reduce Programming with Hadoop
Introduction to Map-Reduce Programming with HadoopDilum Bandara
 
Embarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel ProblemsEmbarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel ProblemsDilum Bandara
 
Introduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale ComputersIntroduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale ComputersDilum Bandara
 
Introduction to Thread Level Parallelism
Introduction to Thread Level ParallelismIntroduction to Thread Level Parallelism
Introduction to Thread Level ParallelismDilum Bandara
 
CPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching TechniquesCPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching TechniquesDilum Bandara
 
Data-Level Parallelism in Microprocessors
Data-Level Parallelism in MicroprocessorsData-Level Parallelism in Microprocessors
Data-Level Parallelism in MicroprocessorsDilum Bandara
 
Instruction Level Parallelism – Hardware Techniques
Instruction Level Parallelism – Hardware TechniquesInstruction Level Parallelism – Hardware Techniques
Instruction Level Parallelism – Hardware TechniquesDilum Bandara
 
Instruction Level Parallelism – Compiler Techniques
Instruction Level Parallelism – Compiler TechniquesInstruction Level Parallelism – Compiler Techniques
Instruction Level Parallelism – Compiler TechniquesDilum Bandara
 
CPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An IntroductionCPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An IntroductionDilum Bandara
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
High Performance Networking with Advanced TCP
High Performance Networking with Advanced TCPHigh Performance Networking with Advanced TCP
High Performance Networking with Advanced TCPDilum Bandara
 
Introduction to Content Delivery Networks
Introduction to Content Delivery NetworksIntroduction to Content Delivery Networks
Introduction to Content Delivery NetworksDilum Bandara
 
Peer-to-Peer Networking Systems and Streaming
Peer-to-Peer Networking Systems and StreamingPeer-to-Peer Networking Systems and Streaming
Peer-to-Peer Networking Systems and StreamingDilum Bandara
 

More from Dilum Bandara (20)

Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
 
Time Series Analysis and Forecasting in Practice
Time Series Analysis and Forecasting in PracticeTime Series Analysis and Forecasting in Practice
Time Series Analysis and Forecasting in Practice
 
Introduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCAIntroduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCA
 
Introduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive AnalyticsIntroduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive Analytics
 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data Structures
 
Hard to Paralelize Problems: Matrix-Vector and Matrix-Matrix
Hard to Paralelize Problems: Matrix-Vector and Matrix-MatrixHard to Paralelize Problems: Matrix-Vector and Matrix-Matrix
Hard to Paralelize Problems: Matrix-Vector and Matrix-Matrix
 
Introduction to Map-Reduce Programming with Hadoop
Introduction to Map-Reduce Programming with HadoopIntroduction to Map-Reduce Programming with Hadoop
Introduction to Map-Reduce Programming with Hadoop
 
Embarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel ProblemsEmbarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel Problems
 
Introduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale ComputersIntroduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale Computers
 
Introduction to Thread Level Parallelism
Introduction to Thread Level ParallelismIntroduction to Thread Level Parallelism
Introduction to Thread Level Parallelism
 
CPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching TechniquesCPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching Techniques
 
Data-Level Parallelism in Microprocessors
Data-Level Parallelism in MicroprocessorsData-Level Parallelism in Microprocessors
Data-Level Parallelism in Microprocessors
 
Instruction Level Parallelism – Hardware Techniques
Instruction Level Parallelism – Hardware TechniquesInstruction Level Parallelism – Hardware Techniques
Instruction Level Parallelism – Hardware Techniques
 
Instruction Level Parallelism – Compiler Techniques
Instruction Level Parallelism – Compiler TechniquesInstruction Level Parallelism – Compiler Techniques
Instruction Level Parallelism – Compiler Techniques
 
CPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An IntroductionCPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An Introduction
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
High Performance Networking with Advanced TCP
High Performance Networking with Advanced TCPHigh Performance Networking with Advanced TCP
High Performance Networking with Advanced TCP
 
Introduction to Content Delivery Networks
Introduction to Content Delivery NetworksIntroduction to Content Delivery Networks
Introduction to Content Delivery Networks
 
Peer-to-Peer Networking Systems and Streaming
Peer-to-Peer Networking Systems and StreamingPeer-to-Peer Networking Systems and Streaming
Peer-to-Peer Networking Systems and Streaming
 
Mobile Services
Mobile ServicesMobile Services
Mobile Services
 

Recently uploaded

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 

Recently uploaded (20)

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 

Interprocess Communication

  • 1. Interprocess Communication CS4532 Concurrent Programming Dilum Bandara Dilum.Bandara@uom.lk Slides extended from “Modern Operating Systems” by A. S. Tanenbaum and “The Little Book of Semaphores” by Allen B. Downey
  • 2. Outline  Issues  How 1 process pass data to another  Making sure processes don’t get into each other’s way while engaged in critical activity  Proper sequencing when dependencies are present  Solutions  Semaphores  Mutexes  Monitors  Message Passing  Barriers 2
  • 3. Race Conditions  2 processes want to access shared memory at same time  Race conditions – when 2 or more processes read/write a shared resource & final result depends on who runs correctly  Solution – mutual exclusion 3 Printer daemon
  • 4. Critical Regions  Part of a program where a shared resource is accessed  Make sure no 2 processes are in critical region at same time  avoid race condition  4 conditions to provide mutual exclusion 1. No 2 processes simultaneously in critical region 2. No assumptions made about speeds or no of CPUs 3. No process running outside its critical region may block another process 4. No process must wait forever to enter its critical region 4
  • 5. Critical Regions (Cont.) Mutual exclusion using critical regions 5
  • 6. Supporting Mutual Exclusion  Disabling interrupts  No preemption  What if a process never enable interrupts?  Strict alternation  Strict turns  Lock variables  Single, shared variable  Reading & writing into lock is not atomic 6
  • 7. Mutual Exclusion with Busy Waiting  Proposed solution to critical region problem  (a) Process 0, (b) Process 1  Problems? 7
  • 8. Mutual Exclusion with Busy Waiting (Cont.) Peterson's solution for achieving mutual exclusion 8
  • 9. Mutual Exclusion with Busy Waiting (Cont.)  TSL – Test & set lock  Entering & leaving a critical region using TSL assembly instruction 9
  • 10. Issues with Busy Waiting  Waste CPU time  Unexpected effects  Process h with high priority & process l with low priority  When h is busy waiting l will never get a chance to leave critical region  Solution  Sleep & wakeup 10
  • 11. Sleep & Wakeup Producer-consumer problem with fatal race condition 11 Not atomic
  • 12. Semaphores  Internal Counter capable of providing mutual exclusion & synchronization  Counter can go Up & Down  If down() when counter is zero, thread blocks  When up() counter increases & if there are waiting threads, one of them is released/wakeup 12
  • 13. Semaphores (Cont.)  Integer variable to count no of wakeups saved for future use  0 – no wakeups pending  1+ – 1 or more wakeups pending  Operations  down()  If count > 0, decrement value & continue – atomic  If count = 0, sleep – atomic  up()  If count >= 0 and no one sleeping, increment value & continue – atomic  If count == 0, wakeup one of the sleeping threads – atomic 13
  • 14. Semaphore Implementation If Count Can Be Negative  down()  Decrement value  If count >= 0 continue  Else sleep  up()  Increment value  If count > 0 continue  Else wakeup one of the sleeping threads 14
  • 15. Properties of Semaphores  Semaphores can be initialized to any integer  foo = Semaphore(100)  Binary semaphore  Initialized to 0 & used by 2+ processors to ensure only 1 can enter critical region  After that only allowed operations are up() & down()  foo.up() = foo.signal()  foo.down() = foo.wait()  Usually can’t read current value of a semaphore  When down() is called, if counter = 0, thread is blocked & can’t continue until another thread calls up()  When up() is called, if there are other threads waiting, 1 of them gets unblocked 15
  • 16. Why Semaphores?  Impose deliberate constraints that help programmers avoid errors  Solutions using semaphores are often clean & organized  Make it easy to demonstrate their correctness  Can be implemented efficiently on many systems  Solutions that use semaphores are portable & usually efficient 16
  • 17. Example – Print A before B Lock l Thread 1 Print A l.unlock(); Thread 2 l.lock(); l.lock(); Print B 17 • What if only Thread 1 get executed first? • Fix above solution with Semaphores
  • 18. Fixed Solution With Semaphores Semaphore s = new S(1) Thread 1 Print A s.up(); Thread 2 s.down(); s.down(); Print B 18 • Is there a better way?
  • 19. Exercise Lock lock = new Lock(); Thread1{ Print A lock.unlock() } Thread2{ lock.lock() Print B }  Provide 2 possible outcome of the above program  How can you use semaphore instead of Locks, such that program will print A & B in order 19
  • 20. Mutexes  When a semaphore’s ability to count is not needed  To enforce mutual exclusion  Implementation of mutex_lock & mutex_unlock 20
  • 22. Monitors  Lock & Semaphores to work, code should be well behaved  But we often forget …  Monitors are the solution  Ensure exclusive access to resources, & for synchronizing & communicating among tasks  Natural, elegant, & efficient mechanisms  Especially for systems with shared memory 22
  • 23. Monitors (Cont.)  Collection of variables, data structures, & procedures (entry routines) to support high-level synchronization  Typically, monitor data can be manipulated only through entry routines  Only 1 task at a time can execute any entry routine  Called active task  Ensure exclusive access to resources, & for synchronizing & communicating among tasks  Natural, elegant, & efficient mechanisms  Especially for systems with shared memory 23
  • 24. Monitors (Cont.)  Enforce mutual exclusion by 1. Locking monitor when execution of an entry routine begins 2. Unlocking it when active task voluntarily gives up control of the monitor  If another task invokes an entry routine while monitor is locked, task is blocked until monitor becomes unlocked  Enforced by a library or operating system 24
  • 26. Java Example public class MyMonitor { private final Lock lock = new ReentrantLock(); public void testA() { lock.lock(); try { //Some code } finally { lock.unlock(); } } public int testB() { lock.lock(); try { return 1; } finally { lock.unlock(); } } } 26
  • 27. Advantages of Monitors  All synchronization code is centralized in one location  If already implemented, users don’t need to know how it’s implemented  Code doesn’t depend on number of processes  You don’t need to release something like a mutex, so you can’t forget to do it 27
  • 28. Barriers  Use of a barrier  Processes approaching a barrier  All processes but 1 blocked at barrier  Last process arrives, all are let through  E.g., matrix iterations 28
  • 29. Multiplex  Critical section that let only N threads to enter at a given time  Can implement using a Semaphore initialized to N 29 Source: www.codeproject.com
  • 30. Message Passing – Producer-Consumer Problem with N Messages 30

Editor's Notes

  1. Disable interrupts just before entering critical region – no context switching
  2. What happens when initially turn = 0
  3. Sleep & Wakeup to avoid busy waiting Counter is 0 – so consumer is ready to sleep (inside sleep()) but before it completes the function context switch happens to producer Producer produce & try to wakeup consumer assuming it’s sleeping – but wakeup will not succeed because consumer is still not fully sleeping. Eventually producer produce all 100 items & go to sleep. Finally both will sleep indefnetly
  4. Act like a singleton pattern
  5. ReentrantLock – allow current thread to reenter lock if it wants
  6. Night club example – for fire safety or exclusive