SlideShare a Scribd company logo
Concurrent Programming
Patterns
CS4532 Concurrent Programming
Dilum Bandara
Dilum.Bandara@uom.lk
Some sides adapted from “The Little Book of Semaphores” by Allen B. Downey
and Dr. Srinath Perera
Building Blocks for Synchronization
 Locks
 Monitors
 Semaphores
 Mutex
 Condition Variables
 When, where, & how to use them?
2
Signalling
 When 1 thread signals to another
 Solves serialization problem
 Can implement using a Semaphore
3
Rendezvous
 2 threads rendezvous at a point of execution
 Neither is allowed to proceed until both have
arrived
 Make sure that a1 happens before b2 & b1
happens before a2
 Implement using Semaphores
4
Barrier
 Generalized form of Rendezvous
 All threads must wait till last 1 arrives
5
Barrier Implementation
6
(1)
Classical Problems
 Problems that we learned in OS class
 Real-world problems
 We may find similar problems in OS &
applications
 Solutions are slightly different
 Parallel programming is more of an Art than a
science
 Teach Art is by demonstrating Great examples
 So we learn classical problems
7
Classical Problems (Cont.)
 Producer & Consumer
 Readers & Writers
 Dinning Philosophers
 Cigarette Smokers Problem
8
Producer-Consumer Problem
 Producer produce an item & add it to a data
structure
 Consumer removes an item from data structure
& process it
 Examples
 User input from a keyboard
 Network packets
 What can go wrong?
 Solution? 9
Producer Consumer
Parallel Program Design
 1st think about signaling
 Decide what semaphores you need if any?
 Decide any state you need?
 Think what state(s) needs mutual exclusions
 Problem state vs. signaling state
 Write program
 Look for race conditions & deadlocks?
 Test by considering different scenarios
10
Producer-Consumer Problem (Cont.)
11
Producer Consumer
Producer-Consumer Init
What if a context switch happen after line 4 of producer?
Producer-Consumer Problem (Cont.)
12
Improved Producer
Is no of items consistent at consumers?
Danger of deadlock when you wait for a Semaphore while holding a
Mutex
Producer-Consumer With a Finite
Buffer
 What if finite buffer?
 Fast producer
 Block producer when buffer is full
 Wakeup when at least 1 buffer slot is empty
 What if?
If items >= buffer.size()
block
 But we don’t know value of a Semaphore
13
Producer-Consumer With a Finite
Buffer (Cont.)
 Buffer of size n
 Producer produce cakes & put them in buffer, consumer
eats them
 When producer finds that a buffer is full, it goes to sleep
 When producer finds that a buffer is empty, it add new
cake & wake up a consumer
 If a buffer is empty when consumer comes in, it wake up
producer & go to sleep
14
Source: http://technogems.blogspot.com/2012/09/producer-consumer-in-c.html
Producer-Consumer With a Finite
Buffer
15
Producer Consumer
Producer-Consumer Init
Readers & Writers
 Data structure is accessed by readers & writers
 Readers can co-exists, but only 1 writer can be
writing at a given time
 Very common usecase
 Read/Write lock is derived from this problem
 How to solve this?
 Hint – assume a light switch in a room
16
Readers & Writers (Cont.)
17
Readers & Writers Init
Writers Readers
Are you sure that only 1 reader & many writers may await?
When reader signals roomEmpty is it actually True?
Readers & Writers (Cont.)
 What if readers continue to arrive?
 Writers will starve
 Not a deadlock
 Solution(s)?
 When a Writer come, give it Priority
 Don’t let more than N Readers to go in consequently
18
Writer Priority – 1st Attempt
19
Readers & Writers Init
Lock lock; Lock empty;
Semaphore wChance = S(1);
int readers = 0;
1. wChance.down();
2. empty.acquire();
3. //write
4. wChance.up();
5. empty.release();
1. wChance.down();
2. wChance.up();
3. lock.acquire();
4. readers = readers +1;
5. if(readers == 1)
6. empty.acquire();
7. lock.release();
9. //read
10. lock.acquire();
11. readers = readers -1;
12. if(readers == 0)
13. empty.release();
14. lock.release();
Writers
Readers
Is writer priority guaranteed?
Light Switch
20
Writer Priority – 2nd Attempt
21
Readers & Writers Init
Writers Readers
Will readers starve?
Dinning Philosophers
 Philosophers eat/think
 Eating needs 2 forks
 Pick one fork at a time
 How to prevent deadlock? 22
Constraints That Dinning Philosophers
Must Satisfy
1. Only 1 philosopher can hold a fork at a time
2. Must be impossible for a deadlock to occur
3. Must be impossible for a philosopher to starve
waiting for a fork
4. Must be possible for more than 1 philosopher to
eat at the same time
 Efficiency
23
Dinning Philosophers – 1st Attempt
24
Which constraints are satisfied?
Dinning Philosophers – 2nd Attempt
 Attack the deadlock
 Possible solutions
 Only 4 Philosophers are allowed to eat at a time
 1 Philosopher is left-handed while others are right-
handed
 Actually, only need at least 1 leftie & at least 1 rightie
25
Only 4 Philosophers Allowed to Eat
26
Footman is a
Multiplex that
controls no of
Philosophers
No deadlock
No starvation
Tanenbaum’s Solution (Part 1/2)
27
Tanenbaum’s Solution (Part 2/2)
28
Tanenbaum’s Solution
29
Not starvation free
Initially 2 & 4 eating
2  1 & 4  3 & process continues

More Related Content

Similar to Concurrent Programming Patterns

Is Python still production ready ? Ludovic Gasc
Is Python still production ready ? Ludovic GascIs Python still production ready ? Ludovic Gasc
Is Python still production ready ? Ludovic Gasc
Pôle Systematic Paris-Region
 
Process Synchronization -1.ppt
Process Synchronization -1.pptProcess Synchronization -1.ppt
Process Synchronization -1.ppt
jayverma27
 
Concurrency
ConcurrencyConcurrency
Concurrency
Isaac Liao
 
Slot03 concurrency2
Slot03 concurrency2Slot03 concurrency2
Slot03 concurrency2
Viên Mai
 
Introduction à kafka
Introduction à kafkaIntroduction à kafka
Introduction à kafka
univalence
 
Apple IT Managing Containers
Apple IT Managing Containers Apple IT Managing Containers
Apple IT Managing Containers
Claire Priester Papas
 
Triage Presentation
Triage PresentationTriage Presentation
Triage Presentation
AashishBalaji1
 
UNIT III Process Synchronization.docx
UNIT III Process Synchronization.docxUNIT III Process Synchronization.docx
UNIT III Process Synchronization.docx
karthikaparthasarath
 
Deadlock _Classic problems.pptx
Deadlock _Classic problems.pptxDeadlock _Classic problems.pptx
Deadlock _Classic problems.pptx
GopikaS12
 
AppSec USA 2014 talk by Chris Swan "Implications & Opportunities at the Bleed...
AppSec USA 2014 talk by Chris Swan "Implications & Opportunities at the Bleed...AppSec USA 2014 talk by Chris Swan "Implications & Opportunities at the Bleed...
AppSec USA 2014 talk by Chris Swan "Implications & Opportunities at the Bleed...
Cohesive Networks
 
Cs 704 d set3
Cs 704 d set3Cs 704 d set3
Cs 704 d set3
Debasis Das
 
Producer consumer.docx
Producer consumer.docxProducer consumer.docx
Producer consumer.docx
Abhishek361641
 
Chapter three- Process Synchronization.ppt
Chapter three- Process Synchronization.pptChapter three- Process Synchronization.ppt
Chapter three- Process Synchronization.ppt
ruhamadana111
 
Ipc feb4
Ipc feb4Ipc feb4
Ipc feb4
yashnand
 
Kernel locking
Kernel lockingKernel locking
Kernel locking
Kalimuthu Velappan
 
The Java Learning Kit Chapter 1 – Introduction Copyri.docx
The Java Learning Kit Chapter 1 – Introduction Copyri.docxThe Java Learning Kit Chapter 1 – Introduction Copyri.docx
The Java Learning Kit Chapter 1 – Introduction Copyri.docx
arnoldmeredith47041
 
Apache Kafka – (Pattern and) Anti-Pattern
Apache Kafka – (Pattern and) Anti-PatternApache Kafka – (Pattern and) Anti-Pattern
Apache Kafka – (Pattern and) Anti-Pattern
confluent
 
The Beam Vision for Portability: "Write once run anywhere"
The Beam Vision for Portability: "Write once run anywhere"The Beam Vision for Portability: "Write once run anywhere"
The Beam Vision for Portability: "Write once run anywhere"
Knoldus Inc.
 
Middle Out Design
Middle Out DesignMiddle Out Design
Middle Out Design
Audrey Crane
 
International Institute of technology (android)
International Institute of technology (android)International Institute of technology (android)
International Institute of technology (android)
Nazih Heni
 

Similar to Concurrent Programming Patterns (20)

Is Python still production ready ? Ludovic Gasc
Is Python still production ready ? Ludovic GascIs Python still production ready ? Ludovic Gasc
Is Python still production ready ? Ludovic Gasc
 
Process Synchronization -1.ppt
Process Synchronization -1.pptProcess Synchronization -1.ppt
Process Synchronization -1.ppt
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Slot03 concurrency2
Slot03 concurrency2Slot03 concurrency2
Slot03 concurrency2
 
Introduction à kafka
Introduction à kafkaIntroduction à kafka
Introduction à kafka
 
Apple IT Managing Containers
Apple IT Managing Containers Apple IT Managing Containers
Apple IT Managing Containers
 
Triage Presentation
Triage PresentationTriage Presentation
Triage Presentation
 
UNIT III Process Synchronization.docx
UNIT III Process Synchronization.docxUNIT III Process Synchronization.docx
UNIT III Process Synchronization.docx
 
Deadlock _Classic problems.pptx
Deadlock _Classic problems.pptxDeadlock _Classic problems.pptx
Deadlock _Classic problems.pptx
 
AppSec USA 2014 talk by Chris Swan "Implications & Opportunities at the Bleed...
AppSec USA 2014 talk by Chris Swan "Implications & Opportunities at the Bleed...AppSec USA 2014 talk by Chris Swan "Implications & Opportunities at the Bleed...
AppSec USA 2014 talk by Chris Swan "Implications & Opportunities at the Bleed...
 
Cs 704 d set3
Cs 704 d set3Cs 704 d set3
Cs 704 d set3
 
Producer consumer.docx
Producer consumer.docxProducer consumer.docx
Producer consumer.docx
 
Chapter three- Process Synchronization.ppt
Chapter three- Process Synchronization.pptChapter three- Process Synchronization.ppt
Chapter three- Process Synchronization.ppt
 
Ipc feb4
Ipc feb4Ipc feb4
Ipc feb4
 
Kernel locking
Kernel lockingKernel locking
Kernel locking
 
The Java Learning Kit Chapter 1 – Introduction Copyri.docx
The Java Learning Kit Chapter 1 – Introduction Copyri.docxThe Java Learning Kit Chapter 1 – Introduction Copyri.docx
The Java Learning Kit Chapter 1 – Introduction Copyri.docx
 
Apache Kafka – (Pattern and) Anti-Pattern
Apache Kafka – (Pattern and) Anti-PatternApache Kafka – (Pattern and) Anti-Pattern
Apache Kafka – (Pattern and) Anti-Pattern
 
The Beam Vision for Portability: "Write once run anywhere"
The Beam Vision for Portability: "Write once run anywhere"The Beam Vision for Portability: "Write once run anywhere"
The Beam Vision for Portability: "Write once run anywhere"
 
Middle Out Design
Middle Out DesignMiddle Out Design
Middle Out Design
 
International Institute of technology (android)
International Institute of technology (android)International Institute of technology (android)
International Institute of technology (android)
 

More from Dilum Bandara

Introduction to Machine Learning
Introduction to Machine LearningIntroduction to Machine Learning
Introduction to Machine Learning
Dilum 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 Practice
Dilum Bandara
 
Introduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCAIntroduction to Dimension Reduction with PCA
Introduction to Dimension Reduction with PCA
Dilum Bandara
 
Introduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive AnalyticsIntroduction to Descriptive & Predictive Analytics
Introduction to Descriptive & Predictive Analytics
Dilum Bandara
 
Introduction to Concurrent Data Structures
Introduction to Concurrent Data StructuresIntroduction to Concurrent Data Structures
Introduction to Concurrent Data Structures
Dilum 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-Matrix
Dilum 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 Hadoop
Dilum Bandara
 
Embarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel ProblemsEmbarrassingly/Delightfully Parallel Problems
Embarrassingly/Delightfully Parallel Problems
Dilum Bandara
 
Introduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale ComputersIntroduction to Warehouse-Scale Computers
Introduction to Warehouse-Scale Computers
Dilum Bandara
 
Introduction to Thread Level Parallelism
Introduction to Thread Level ParallelismIntroduction to Thread Level Parallelism
Introduction to Thread Level Parallelism
Dilum Bandara
 
CPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching TechniquesCPU Memory Hierarchy and Caching Techniques
CPU Memory Hierarchy and Caching Techniques
Dilum Bandara
 
Data-Level Parallelism in Microprocessors
Data-Level Parallelism in MicroprocessorsData-Level Parallelism in Microprocessors
Data-Level Parallelism in Microprocessors
Dilum Bandara
 
Instruction Level Parallelism – Hardware Techniques
Instruction Level Parallelism – Hardware TechniquesInstruction Level Parallelism – Hardware Techniques
Instruction Level Parallelism – Hardware Techniques
Dilum Bandara
 
Instruction Level Parallelism – Compiler Techniques
Instruction Level Parallelism – Compiler TechniquesInstruction Level Parallelism – Compiler Techniques
Instruction Level Parallelism – Compiler Techniques
Dilum Bandara
 
CPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An IntroductionCPU Pipelining and Hazards - An Introduction
CPU Pipelining and Hazards - An Introduction
Dilum Bandara
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
Dilum Bandara
 
High Performance Networking with Advanced TCP
High Performance Networking with Advanced TCPHigh Performance Networking with Advanced TCP
High Performance Networking with Advanced TCP
Dilum Bandara
 
Introduction to Content Delivery Networks
Introduction to Content Delivery NetworksIntroduction to Content Delivery Networks
Introduction to Content Delivery Networks
Dilum 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 Streaming
Dilum Bandara
 
Mobile Services
Mobile ServicesMobile Services
Mobile Services
Dilum 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

What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
Envertis Software Solutions
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
Severalnines
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
XfilesPro
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
Patrick Weigel
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
aeeva
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
Alina Yurenko
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
Alberto Brandolini
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
OnePlan Solutions
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
Yara Milbes
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
ToXSL Technologies
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
kalichargn70th171
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
narinav14
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
safelyiotech
 

Recently uploaded (20)

What’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete RoadmapWhat’s New in Odoo 17 – A Complete Roadmap
What’s New in Odoo 17 – A Complete Roadmap
 
Kubernetes at Scale: Going Multi-Cluster with Istio
Kubernetes at Scale:  Going Multi-Cluster  with IstioKubernetes at Scale:  Going Multi-Cluster  with Istio
Kubernetes at Scale: Going Multi-Cluster with Istio
 
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...
 
WWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders AustinWWDC 2024 Keynote Review: For CocoaCoders Austin
WWDC 2024 Keynote Review: For CocoaCoders Austin
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
TMU毕业证书精仿办理
TMU毕业证书精仿办理TMU毕业证书精仿办理
TMU毕业证书精仿办理
 
All you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVMAll you need to know about Spring Boot and GraalVM
All you need to know about Spring Boot and GraalVM
 
Modelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - AmsterdamModelling Up - DDDEurope 2024 - Amsterdam
Modelling Up - DDDEurope 2024 - Amsterdam
 
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...Transforming Product Development using OnePlan To Boost Efficiency and Innova...
Transforming Product Development using OnePlan To Boost Efficiency and Innova...
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024The Rising Future of CPaaS in the Middle East 2024
The Rising Future of CPaaS in the Middle East 2024
 
How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?How Can Hiring A Mobile App Development Company Help Your Business Grow?
How Can Hiring A Mobile App Development Company Help Your Business Grow?
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
The Power of Visual Regression Testing_ Why It Is Critical for Enterprise App...
 
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and MoreManyata Tech Park Bangalore_ Infrastructure, Facilities and More
Manyata Tech Park Bangalore_ Infrastructure, Facilities and More
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
Safelyio Toolbox Talk Softwate & App (How To Digitize Safety Meetings)
 

Concurrent Programming Patterns

  • 1. Concurrent Programming Patterns CS4532 Concurrent Programming Dilum Bandara Dilum.Bandara@uom.lk Some sides adapted from “The Little Book of Semaphores” by Allen B. Downey and Dr. Srinath Perera
  • 2. Building Blocks for Synchronization  Locks  Monitors  Semaphores  Mutex  Condition Variables  When, where, & how to use them? 2
  • 3. Signalling  When 1 thread signals to another  Solves serialization problem  Can implement using a Semaphore 3
  • 4. Rendezvous  2 threads rendezvous at a point of execution  Neither is allowed to proceed until both have arrived  Make sure that a1 happens before b2 & b1 happens before a2  Implement using Semaphores 4
  • 5. Barrier  Generalized form of Rendezvous  All threads must wait till last 1 arrives 5
  • 7. Classical Problems  Problems that we learned in OS class  Real-world problems  We may find similar problems in OS & applications  Solutions are slightly different  Parallel programming is more of an Art than a science  Teach Art is by demonstrating Great examples  So we learn classical problems 7
  • 8. Classical Problems (Cont.)  Producer & Consumer  Readers & Writers  Dinning Philosophers  Cigarette Smokers Problem 8
  • 9. Producer-Consumer Problem  Producer produce an item & add it to a data structure  Consumer removes an item from data structure & process it  Examples  User input from a keyboard  Network packets  What can go wrong?  Solution? 9 Producer Consumer
  • 10. Parallel Program Design  1st think about signaling  Decide what semaphores you need if any?  Decide any state you need?  Think what state(s) needs mutual exclusions  Problem state vs. signaling state  Write program  Look for race conditions & deadlocks?  Test by considering different scenarios 10
  • 11. Producer-Consumer Problem (Cont.) 11 Producer Consumer Producer-Consumer Init What if a context switch happen after line 4 of producer?
  • 12. Producer-Consumer Problem (Cont.) 12 Improved Producer Is no of items consistent at consumers? Danger of deadlock when you wait for a Semaphore while holding a Mutex
  • 13. Producer-Consumer With a Finite Buffer  What if finite buffer?  Fast producer  Block producer when buffer is full  Wakeup when at least 1 buffer slot is empty  What if? If items >= buffer.size() block  But we don’t know value of a Semaphore 13
  • 14. Producer-Consumer With a Finite Buffer (Cont.)  Buffer of size n  Producer produce cakes & put them in buffer, consumer eats them  When producer finds that a buffer is full, it goes to sleep  When producer finds that a buffer is empty, it add new cake & wake up a consumer  If a buffer is empty when consumer comes in, it wake up producer & go to sleep 14 Source: http://technogems.blogspot.com/2012/09/producer-consumer-in-c.html
  • 15. Producer-Consumer With a Finite Buffer 15 Producer Consumer Producer-Consumer Init
  • 16. Readers & Writers  Data structure is accessed by readers & writers  Readers can co-exists, but only 1 writer can be writing at a given time  Very common usecase  Read/Write lock is derived from this problem  How to solve this?  Hint – assume a light switch in a room 16
  • 17. Readers & Writers (Cont.) 17 Readers & Writers Init Writers Readers Are you sure that only 1 reader & many writers may await? When reader signals roomEmpty is it actually True?
  • 18. Readers & Writers (Cont.)  What if readers continue to arrive?  Writers will starve  Not a deadlock  Solution(s)?  When a Writer come, give it Priority  Don’t let more than N Readers to go in consequently 18
  • 19. Writer Priority – 1st Attempt 19 Readers & Writers Init Lock lock; Lock empty; Semaphore wChance = S(1); int readers = 0; 1. wChance.down(); 2. empty.acquire(); 3. //write 4. wChance.up(); 5. empty.release(); 1. wChance.down(); 2. wChance.up(); 3. lock.acquire(); 4. readers = readers +1; 5. if(readers == 1) 6. empty.acquire(); 7. lock.release(); 9. //read 10. lock.acquire(); 11. readers = readers -1; 12. if(readers == 0) 13. empty.release(); 14. lock.release(); Writers Readers Is writer priority guaranteed?
  • 21. Writer Priority – 2nd Attempt 21 Readers & Writers Init Writers Readers Will readers starve?
  • 22. Dinning Philosophers  Philosophers eat/think  Eating needs 2 forks  Pick one fork at a time  How to prevent deadlock? 22
  • 23. Constraints That Dinning Philosophers Must Satisfy 1. Only 1 philosopher can hold a fork at a time 2. Must be impossible for a deadlock to occur 3. Must be impossible for a philosopher to starve waiting for a fork 4. Must be possible for more than 1 philosopher to eat at the same time  Efficiency 23
  • 24. Dinning Philosophers – 1st Attempt 24 Which constraints are satisfied?
  • 25. Dinning Philosophers – 2nd Attempt  Attack the deadlock  Possible solutions  Only 4 Philosophers are allowed to eat at a time  1 Philosopher is left-handed while others are right- handed  Actually, only need at least 1 leftie & at least 1 rightie 25
  • 26. Only 4 Philosophers Allowed to Eat 26 Footman is a Multiplex that controls no of Philosophers No deadlock No starvation
  • 29. Tanenbaum’s Solution 29 Not starvation free Initially 2 & 4 eating 2  1 & 4  3 & process continues