SlideShare a Scribd company logo
Writing Concurrent Programs
Using Basic Constructs
CS4532 Concurrent Programming
Dilum Bandara
Dilum.Bandara@uom.lk
Some sides adapted from Dr. Srinath Perera, WSO2 and
“The Art of Multiprocessor Programming” by Maurice Herlihy & Nir Shavit Slightly
Outline
 Locks
 Monitors
 Semaphores
 Mutex
 Conditional Variables
2
Why Concurrent Programming is
Hard?
 Threads/processes often need to share data
 Data consistency
 Enforced through critical sections/atomic operations
 E.g., preventing race conditions
 Cooperation (synchronization)
 Control the way programs makes progress
 E.g., producer consumer problem
 This is complicated by lack of timing
guarantees
 Cache misses, page faults, context switches
 Threads are scheduled by OS or thread library
3
Source: www.grype.ca
How Things Can Go Wrong?
int balance = 200;
Thread1{
run(){
if(balance >= 100){
balance = balance - 100;
System.out.println("Withdraw 100, balance "+ balance);
}else{
System.out.println("Insufficient Balance "+ balance);
}
}
}
Thread2{
run(){
if(balance >= 200){
balance = balance - 200;
System.out.println("Withdraw 200, balance "+ balance);
}else{
System.out.println("Insufficient Balance "+ balance);
}
}
} 4
Mutual Exclusion & Synchronization
 Mutual Exclusion
 Ensure at most 1 thread can be in critical section at
any given time
 Achieved via Atomic Operations
 Use Locks, Monitors, & Mutexs
 Synchronization
 Making sure different threads are in sync with each
other
 E.g, producer consumer problem, reads & writers problem
 Use Semaphores & some patterns
5
Withdraw Problem with Locks –
Alice & Bob have a shared account
int ac1 = 200;
int ac2 = 100;
Alice:
if(ac1 >= 100){
ac1 = ac1 - 100;
}
Print (balance)
Bob:
if(ac1 >= 100){
ac1 = ac1 - 100;
}
Print (balance)
6
Alice & Bob have 2 shared accounts,
how to extend above to 2 accounts?
int ac1 = 200;
int ac2 = 100;
Alice:
if(ac1 >= 100){
ac1 = ac1 - 100;
}
if(ac2 >= 100){
ac2 = ac2 - 100;
}
Print (balance)
Bob:
if(ac1 >= 100){
ac1 = ac1 - 100;
}
if(ac2 >= 100){
ac2 = ac2 - 100;
}
Print (balance) 7
Withdraw Problem with Monitors
Account{
int balance;
void synchronized withdraw(int amount){
if(balance >= amount){
balance = balance - amount;
}
}
}
 “Synchronized” keyword of Java does the same thing
8
Condition Variables
 Allows checking for a condition
 Operations are called wait() & signal()
 Idea is similar to sleep() & wakeup()
 wait() & notify() in Java
 Usually wake up only 1 blocked thread
 Also have a broadcast(), which wakes up everyone
 Threads can wait by calling wait()
 1 of them is released when signal() is called
 Once signaled, the event is lost
9
Exercise – Condition Variables
 Write a program so that program will always
print A before B, using condition variable(s)
 i.e., wait() & notify()
Thread 1 Thread 2
Print A Print B
10
Exercise – Condition Variables (Cont.)
CV cv;
Thread 1 Thread 2
Print A cv.wait()
cv.notify() Print B
11
Will this work?
What if notify() before wait()?
Exercise – Condition Variables (Cont.)
CV cv;
Lock l;
Boolean done = False;
Thread 1 Thread 2
Print A l.lock()
l.lock() if(!done)
done = True cv.wait()
l.unlock() l.unlock()
cv.notify() Print B
12
Is the lock essential?
Will this work?
Exercise – Condition Variables (Cont.)
CV cv;
Lock l;
Boolean done = False;
Thread 1 Thread 2
Print A Synchronized {
Synchronized { if(!done)
done = True cv.wait()
} }
cv.notify() Print B
13
Is the lock essential?
Will this work?
Implement a Semaphore with Locks &
Condition Variables
up(){
synchronized(){
val++;
if (val <= 0){
cv.signal();
}
}
}
down(){
synchronized(){
val--;
if(val < 0){
cv.wait();
}
}
}
14
CV cv;
int val = 0;
Will this work?
Parallel Program Design
 Is signaling required?
 Decide what semaphores you need, if any
 Decide any state you need
 What states need mutual exclusion?
 Problem state vs. signaling state
 Write program
 Test by considering different scenarios
 Sequential case & concurrent case
 Any race conditions & deadlocks?
15

More Related Content

Similar to Writing Concurrent Programs

Java tut1
Java tut1Java tut1
Java tut1
Ajmal Khan
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Vijay A Raj
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
Abdul Aziz
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
guest5c8bd1
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
Suman Karumuri
 
operating system question bank
operating system question bankoperating system question bank
operating system question bank
rajatdeep kaur
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
ArnaldoCanelas
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
Govind Samleti
 
Java tut1
Java tut1Java tut1
Java tut1
Sumit Tambe
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
Java tut1
Java tut1Java tut1
Java tut1
Sumit Tambe
 
Javatut1
Javatut1 Javatut1
Javatut1
desaigeeta
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
Bui Kiet
 
Slides for OS 06-Sync.pdf
Slides for OS 06-Sync.pdfSlides for OS 06-Sync.pdf
Slides for OS 06-Sync.pdf
GeekyHassan
 
Concurrent Rendering Adventures in React 18
Concurrent Rendering Adventures in React 18Concurrent Rendering Adventures in React 18
Concurrent Rendering Adventures in React 18
Maurice De Beijer [MVP]
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
control statements
control statementscontrol statements
control statements
Azeem Sultan
 
Module-related pages
Module-related pagesModule-related pages
Module-related pagesbutest
 
Module-related pages
Module-related pagesModule-related pages
Module-related pages
butest
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
HongAnhNguyn285885
 

Similar to Writing Concurrent Programs (20)

Java tut1
Java tut1Java tut1
Java tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
 
operating system question bank
operating system question bankoperating system question bank
operating system question bank
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Slides for OS 06-Sync.pdf
Slides for OS 06-Sync.pdfSlides for OS 06-Sync.pdf
Slides for OS 06-Sync.pdf
 
Concurrent Rendering Adventures in React 18
Concurrent Rendering Adventures in React 18Concurrent Rendering Adventures in React 18
Concurrent Rendering Adventures in React 18
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
control statements
control statementscontrol statements
control statements
 
Module-related pages
Module-related pagesModule-related pages
Module-related pages
 
Module-related pages
Module-related pagesModule-related pages
Module-related pages
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 

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

WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
Luigi Fugaro
 
DevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps ServicesDevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps Services
seospiralmantra
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
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
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
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
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
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
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
Bert Jan Schrijver
 
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
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
campbellclarkson
 
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
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
Paul Brebner
 
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 Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.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
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
brainerhub1
 
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
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid
 

Recently uploaded (20)

WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
WMF 2024 - Unlocking the Future of Data Powering Next-Gen AI with Vector Data...
 
DevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps ServicesDevOps Consulting Company | Hire DevOps Services
DevOps Consulting Company | Hire DevOps Services
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
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
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
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...
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
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 !
 
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
J-Spring 2024 - Going serverless with Quarkus, GraalVM native images and AWS ...
 
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
 
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
🏎️Tech Transformation: DevOps Insights from the Experts 👩‍💻
 
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
 
Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...Superpower Your Apache Kafka Applications Development with Complementary Open...
Superpower Your Apache Kafka Applications Development with Complementary Open...
 
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 Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.pdfThe Comprehensive Guide to Validating Audio-Visual Performances.pdf
The Comprehensive Guide to Validating Audio-Visual Performances.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
 
Unveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdfUnveiling the Advantages of Agile Software Development.pdf
Unveiling the Advantages of Agile Software Development.pdf
 
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?
 
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdfBaha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
Baha Majid WCA4Z IBM Z Customer Council Boston June 2024.pdf
 

Writing Concurrent Programs

  • 1. Writing Concurrent Programs Using Basic Constructs CS4532 Concurrent Programming Dilum Bandara Dilum.Bandara@uom.lk Some sides adapted from Dr. Srinath Perera, WSO2 and “The Art of Multiprocessor Programming” by Maurice Herlihy & Nir Shavit Slightly
  • 2. Outline  Locks  Monitors  Semaphores  Mutex  Conditional Variables 2
  • 3. Why Concurrent Programming is Hard?  Threads/processes often need to share data  Data consistency  Enforced through critical sections/atomic operations  E.g., preventing race conditions  Cooperation (synchronization)  Control the way programs makes progress  E.g., producer consumer problem  This is complicated by lack of timing guarantees  Cache misses, page faults, context switches  Threads are scheduled by OS or thread library 3 Source: www.grype.ca
  • 4. How Things Can Go Wrong? int balance = 200; Thread1{ run(){ if(balance >= 100){ balance = balance - 100; System.out.println("Withdraw 100, balance "+ balance); }else{ System.out.println("Insufficient Balance "+ balance); } } } Thread2{ run(){ if(balance >= 200){ balance = balance - 200; System.out.println("Withdraw 200, balance "+ balance); }else{ System.out.println("Insufficient Balance "+ balance); } } } 4
  • 5. Mutual Exclusion & Synchronization  Mutual Exclusion  Ensure at most 1 thread can be in critical section at any given time  Achieved via Atomic Operations  Use Locks, Monitors, & Mutexs  Synchronization  Making sure different threads are in sync with each other  E.g, producer consumer problem, reads & writers problem  Use Semaphores & some patterns 5
  • 6. Withdraw Problem with Locks – Alice & Bob have a shared account int ac1 = 200; int ac2 = 100; Alice: if(ac1 >= 100){ ac1 = ac1 - 100; } Print (balance) Bob: if(ac1 >= 100){ ac1 = ac1 - 100; } Print (balance) 6
  • 7. Alice & Bob have 2 shared accounts, how to extend above to 2 accounts? int ac1 = 200; int ac2 = 100; Alice: if(ac1 >= 100){ ac1 = ac1 - 100; } if(ac2 >= 100){ ac2 = ac2 - 100; } Print (balance) Bob: if(ac1 >= 100){ ac1 = ac1 - 100; } if(ac2 >= 100){ ac2 = ac2 - 100; } Print (balance) 7
  • 8. Withdraw Problem with Monitors Account{ int balance; void synchronized withdraw(int amount){ if(balance >= amount){ balance = balance - amount; } } }  “Synchronized” keyword of Java does the same thing 8
  • 9. Condition Variables  Allows checking for a condition  Operations are called wait() & signal()  Idea is similar to sleep() & wakeup()  wait() & notify() in Java  Usually wake up only 1 blocked thread  Also have a broadcast(), which wakes up everyone  Threads can wait by calling wait()  1 of them is released when signal() is called  Once signaled, the event is lost 9
  • 10. Exercise – Condition Variables  Write a program so that program will always print A before B, using condition variable(s)  i.e., wait() & notify() Thread 1 Thread 2 Print A Print B 10
  • 11. Exercise – Condition Variables (Cont.) CV cv; Thread 1 Thread 2 Print A cv.wait() cv.notify() Print B 11 Will this work? What if notify() before wait()?
  • 12. Exercise – Condition Variables (Cont.) CV cv; Lock l; Boolean done = False; Thread 1 Thread 2 Print A l.lock() l.lock() if(!done) done = True cv.wait() l.unlock() l.unlock() cv.notify() Print B 12 Is the lock essential? Will this work?
  • 13. Exercise – Condition Variables (Cont.) CV cv; Lock l; Boolean done = False; Thread 1 Thread 2 Print A Synchronized { Synchronized { if(!done) done = True cv.wait() } } cv.notify() Print B 13 Is the lock essential? Will this work?
  • 14. Implement a Semaphore with Locks & Condition Variables up(){ synchronized(){ val++; if (val <= 0){ cv.signal(); } } } down(){ synchronized(){ val--; if(val < 0){ cv.wait(); } } } 14 CV cv; int val = 0; Will this work?
  • 15. Parallel Program Design  Is signaling required?  Decide what semaphores you need, if any  Decide any state you need  What states need mutual exclusion?  Problem state vs. signaling state  Write program  Test by considering different scenarios  Sequential case & concurrent case  Any race conditions & deadlocks? 15