SlideShare a Scribd company logo
• PRODUCER AND CONSUMER PROBLEM
• READERS/WRITER PROBLEM
Submitted By,
Ambooj Yadav
&
Hina Firdaus
M.Tech CSE, 1st
year
What is the need of synchronization?
For getting shared access to resources (variables, buffers,
devices, etc.)
For interruptless communicating
Cases where cooperating processes need not
synchronize to share resources:
All processes are read only.
All processes are write only.
One process writes, all other processes read.
In synchronization we will discuss two problem
mainly:-
Producer and Consumer problem
Readers and writers problem
Problem and Consumer system:
It is a system where one system produce items that will be
used by other system.
Examples
shared printer, the printer here acts the consumer, and
the computers that produce the documents to be
printed are the consumers.
Sensors network, where the sensors here the producers,
and the base stations (sink) are the producers.
It is also called bounded buffer problem .
The producer-consumer problem illustrates the need for
synchronization in systems where many processes share a
resource.
In the problem, two processes share a fixed-size buffer.
One process produces information and puts it in the
buffer, while the other process consumes information
from the buffer.
These processes do not take turns accessing the buffer,
they both work concurrently.
Start by imagining an unbounded (infinite) buffer
Producer process writes data to buffer
 Writes to In and moves rightwards
Consumer process reads data from buffer
 Reads from Out and moves rightwards
 Should not try to consume if there is no data
Bounded buffer: size ‘N’
 Access entry 0… N-1, then “wrap around” to 0 again
Producer process writes data to buffer
 Must not write more than ‘N’ items more than consumer “ate”
Consumer process reads data from buffer
 Should not try to consume if there is no data
Pseudo code for Producer:
While(Items_number ==buffer size);
//waiting since the buffer is full
Buffer[i]=next_produced_item;
i=(i+1)%Buffer_size;
Items_number++;
Pseudo code for Consumer:
while (Items_number == 0 ;
// do nothing since the buffer is empty
Consumed _item= buffer[j];
j = (j + 1) % Buffer_size;
Items_number--;
A number of applications:
 Data from bar-code reader consumed by device driver
 Data in a file you want to print consumed by printer spooler,
which produces data consumed by line printer device driver
 Web server produces data consumed by client’s web browser
Thought questions: where’s the bounded buffer?
Solving with semaphores
We’ll use two kinds of semaphores
We’ll use counters to track how much data is in the
buffer
One counter counts as we add data and stops the producer if
there are N objects in the buffer
A second counter counts as we remove data and stops a
consumer if there are 0 in the buffer
Idea: since general semaphores can count for us, we
don’t need a separate counter variable
Why do we need a second kind of semaphore?
We’ll also need a mutex semaphore
Shared: Semaphores mutex, empty, full;
Init: mutex = 1; /* for mutual exclusion*/
empty = N; /* number empty buf entries */
full = 0; /* number full buf entries */
Producer
do {
. . .
// produce an item in nextp
. . .
P(empty);
P(mutex);
. . .
// add nextp to buffer
. . .
V(mutex);
V(full);
} while (true);
Consumer
do {
P(full);
P(mutex);
. . .
// remove item to nextc
. . .
V(mutex);
V(empty);
. . .
// consume item in nextc
. . .
} while (true);
Monitor: object with a set of monitor procedures and
only one thread may be active (i.e. running one of the
monitor procedures) at a time
Compiler automatically inserts lock and unlock
operations upon entry and exit of monitor procedures
Two condition variables
has_empty: buffer has at
least one empty slot
has_full: buffer has at
least one full slot
nfull: number of filled
slots
Need to do our own
counting for condition
variables
Semaphores are sticky: they have memory,
sem_post() will increment the semaphore counter,
even if no one has called sem_wait()
Condition variables are not: if no one is waiting for a
signal(), this signal() is not saved
 Despite the difference, they are as powerful
Wait(s) and signal(s) are scattered among several
processes therefore it is difficult to understand their effect.
Usage must be correct in all the processes.
One bad process or one program error can kill the whole
system.
R
R
R
W
A data set is shared among a number of concurrent
processes
Readers – only read the data set; they do not
perform any updates
Writers – can both read and write.
Many threads share an object in memory
Some write to it, some only read it
Only one writer can be active at a time
Any number of readers can be active
simultaneously
One issue we need to settle, to clarify problem
statement.
Suppose that a writer is active and a mixture of readers
and writers now shows up. Who should get in next?
Or suppose that a writer is waiting and an endless of
stream of readers keeps showing up. Is it fair for them
to become active?
We’ll favor a kind of back-and-forth form of
fairness:
Once a reader is waiting, readers will get in next.
If a writer is waiting, one writer will get in next.
Example: making an airline reservation
 When you browse to look at flight schedules the web site is acting
as a reader on your behalf
 When you reserve a seat, the web site has to write into the
database to make the reservation
 a web server cache needs to quickly serve the same static page for
many thousands of requests. Occasionally however an author may
decide to update the page.
The structure of a Readers-writers process using mutex:
Shared variables: Semaphore mutex, wrl;
integer rcount;
Init: mutex = 1, wrl = 1, rcount = 0;
Writer
do {
P(wrl);
. . .
/*writing is performed*/
. . .
V(wrl);
}while(TRUE);
Reader
do {
P(wrl);
. . .
/*Reading is performed*/
. . .
V(wrl);
}while(TRUE);
The structure of a reader process using semaphore:
do {
P(mutex);
rcount++;
if (rcount == 1)
P(wrl);
V(mutex);
. . .
/*reading is performed*/
. . .
P(mutex);
rcount--;
if (rcount == 0)
V(wrl);
V(mutex);
}while(TRUE);
If there is a writer
 First reader blocks on wrl
 Other readers block on mutex
Once a reader is active, all readers get to go through
 Trick question: Which reader gets in first?
The last reader to exit signals a writer
 If no writer, then readers can continue
If readers and writers waiting on wrl, and writer exits
 Who gets to go in first?
Why doesn’t a writer need to use mutex?
Why doesn’t a
writer need to use
mutex?
If readers are active, no writer can enter
The writers wait doing a P(wrl)
While writer is active, nobody can enter
Any other reader or writer will wait
But back-and-forth switching is buggy:
Any number of readers can enter in a row
Readers can “starve” writers
With semaphores, building a solution that has the
desired back-and-forth behavior is really, really
tricky!
We recommend that you try, but not too hard…
readers-writers : monitor; begin
readercount : integer;
busy : boolean;
OKtoread, OKtowrite : condition;
procedure startread;
Begin
if busy then OKtoread.wait;
readercount := readercount + 1;
OKtoread.signal; (* Once one reader can start, they all can *)
end startread;
procedure endread;
begin readercount := readercount - 1;
if readercount = 0 then OKtowrite.signal;
end endread;
procedure startwrite;
begin
if busy OR readercount != 0 then OKtowrite.wait;
busy := true;
end startwrite;
procedure endwrite;
begin busy := false;
if OKtoread.queue then OKtoread.signal
else OKtowrite.signal;
end endwrite;
begin (* initialization *)
readercount := 0;
busy := false;
end;
end readers-writers;
For proper sychronization, reader processes must call
the startread procedure before accessing the file
(shared resource) and call the endread when the read
is finished.
Likewise, writer processes must call startwrite before
modifying the file and call endwrite when the write is
finished.
The monitor uses the boolean variable busy to
indicate whether a writer is active (i.e., accessing the
file) and readercount to keep track of the number of
active readers.
A writer, on invoking startwrite, proceeds only when
no other writer or readers are active.
 In summary, the reader's priority monitor, while not
permitting a new writer to start when there is a reader
waiting, permits any number of readers to proceed, as
long as there is at least one active reader.
Classic synchronization

More Related Content

Similar to Classic synchronization

parallel Questions & answers
parallel Questions & answersparallel Questions & answers
parallel Questions & answers
Md. Mashiur Rahman
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's types
Nishant Joshi
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
Wayne Jones Jnr
 
Monitor(karthika)
Monitor(karthika)Monitor(karthika)
Monitor(karthika)
Nagarajan
 
Process Synchronization Producer-Consumer ProblemThe purpos.docx
Process Synchronization Producer-Consumer ProblemThe purpos.docxProcess Synchronization Producer-Consumer ProblemThe purpos.docx
Process Synchronization Producer-Consumer ProblemThe purpos.docx
stilliegeorgiana
 
Process Synchronization -1.ppt
Process Synchronization -1.pptProcess Synchronization -1.ppt
Process Synchronization -1.ppt
jayverma27
 
10 Multicore 07
10 Multicore 0710 Multicore 07
10 Multicore 07
timcrack
 
Adsa u4 ver 1.0
Adsa u4 ver 1.0Adsa u4 ver 1.0
Adsa u4 ver 1.0
Dr. C.V. Suresh Babu
 
Classical problems of process synchronization
Classical problems of process synchronizationClassical problems of process synchronization
Classical problems of process synchronization
sangrampatil81
 
readerwriter-190410082551.pdf
readerwriter-190410082551.pdfreaderwriter-190410082551.pdf
readerwriter-190410082551.pdf
RohanThota3
 
Reader/writer problem
Reader/writer problemReader/writer problem
Reader/writer problem
RinkuMonani
 
Os unit 3
Os unit 3Os unit 3
Os unit 3
Krupali Mistry
 
Introduction to reactive programming
Introduction to reactive programmingIntroduction to reactive programming
Introduction to reactive programming
Leapfrog Technology Inc.
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
Minal Maniar
 
Os
OsOs
Os
OsOs
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
NexThoughts Technologies
 
Types or evolution of operating system
Types or evolution of operating systemTypes or evolution of operating system
Types or evolution of operating system
Ekta Bafna
 
Bt0070
Bt0070Bt0070
Bt0070
Simpaly Jha
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
Maxim Volgin
 

Similar to Classic synchronization (20)

parallel Questions & answers
parallel Questions & answersparallel Questions & answers
parallel Questions & answers
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's types
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
 
Monitor(karthika)
Monitor(karthika)Monitor(karthika)
Monitor(karthika)
 
Process Synchronization Producer-Consumer ProblemThe purpos.docx
Process Synchronization Producer-Consumer ProblemThe purpos.docxProcess Synchronization Producer-Consumer ProblemThe purpos.docx
Process Synchronization Producer-Consumer ProblemThe purpos.docx
 
Process Synchronization -1.ppt
Process Synchronization -1.pptProcess Synchronization -1.ppt
Process Synchronization -1.ppt
 
10 Multicore 07
10 Multicore 0710 Multicore 07
10 Multicore 07
 
Adsa u4 ver 1.0
Adsa u4 ver 1.0Adsa u4 ver 1.0
Adsa u4 ver 1.0
 
Classical problems of process synchronization
Classical problems of process synchronizationClassical problems of process synchronization
Classical problems of process synchronization
 
readerwriter-190410082551.pdf
readerwriter-190410082551.pdfreaderwriter-190410082551.pdf
readerwriter-190410082551.pdf
 
Reader/writer problem
Reader/writer problemReader/writer problem
Reader/writer problem
 
Os unit 3
Os unit 3Os unit 3
Os unit 3
 
Introduction to reactive programming
Introduction to reactive programmingIntroduction to reactive programming
Introduction to reactive programming
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
 
Os
OsOs
Os
 
Os
OsOs
Os
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJava
 
Types or evolution of operating system
Types or evolution of operating systemTypes or evolution of operating system
Types or evolution of operating system
 
Bt0070
Bt0070Bt0070
Bt0070
 
RxJava@Android
RxJava@AndroidRxJava@Android
RxJava@Android
 

Recently uploaded

Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
PsychoTech Services
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
spdendr
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
MysoreMuleSoftMeetup
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
heathfieldcps1
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
สมใจ จันสุกสี
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
haiqairshad
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
mulvey2
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 

Recently uploaded (20)

Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...Gender and Mental Health - Counselling and Family Therapy Applications and In...
Gender and Mental Health - Counselling and Family Therapy Applications and In...
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
Solutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptxSolutons Maths Escape Room Spatial .pptx
Solutons Maths Escape Room Spatial .pptx
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47Mule event processing models | MuleSoft Mysore Meetup #47
Mule event processing models | MuleSoft Mysore Meetup #47
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
The basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptxThe basics of sentences session 6pptx.pptx
The basics of sentences session 6pptx.pptx
 
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
คำศัพท์ คำพื้นฐานการอ่าน ภาษาอังกฤษ ระดับชั้น ม.1
 
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skillsspot a liar (Haiqa 146).pptx Technical writhing and presentation skills
spot a liar (Haiqa 146).pptx Technical writhing and presentation skills
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptxC1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
C1 Rubenstein AP HuG xxxxxxxxxxxxxx.pptx
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 

Classic synchronization

  • 1. • PRODUCER AND CONSUMER PROBLEM • READERS/WRITER PROBLEM Submitted By, Ambooj Yadav & Hina Firdaus M.Tech CSE, 1st year
  • 2. What is the need of synchronization? For getting shared access to resources (variables, buffers, devices, etc.) For interruptless communicating Cases where cooperating processes need not synchronize to share resources: All processes are read only. All processes are write only. One process writes, all other processes read.
  • 3. In synchronization we will discuss two problem mainly:- Producer and Consumer problem Readers and writers problem
  • 4. Problem and Consumer system: It is a system where one system produce items that will be used by other system. Examples shared printer, the printer here acts the consumer, and the computers that produce the documents to be printed are the consumers. Sensors network, where the sensors here the producers, and the base stations (sink) are the producers.
  • 5. It is also called bounded buffer problem . The producer-consumer problem illustrates the need for synchronization in systems where many processes share a resource. In the problem, two processes share a fixed-size buffer. One process produces information and puts it in the buffer, while the other process consumes information from the buffer. These processes do not take turns accessing the buffer, they both work concurrently.
  • 6. Start by imagining an unbounded (infinite) buffer Producer process writes data to buffer  Writes to In and moves rightwards Consumer process reads data from buffer  Reads from Out and moves rightwards  Should not try to consume if there is no data
  • 7. Bounded buffer: size ‘N’  Access entry 0… N-1, then “wrap around” to 0 again Producer process writes data to buffer  Must not write more than ‘N’ items more than consumer “ate” Consumer process reads data from buffer  Should not try to consume if there is no data
  • 8. Pseudo code for Producer: While(Items_number ==buffer size); //waiting since the buffer is full Buffer[i]=next_produced_item; i=(i+1)%Buffer_size; Items_number++;
  • 9. Pseudo code for Consumer: while (Items_number == 0 ; // do nothing since the buffer is empty Consumed _item= buffer[j]; j = (j + 1) % Buffer_size; Items_number--;
  • 10. A number of applications:  Data from bar-code reader consumed by device driver  Data in a file you want to print consumed by printer spooler, which produces data consumed by line printer device driver  Web server produces data consumed by client’s web browser Thought questions: where’s the bounded buffer?
  • 11. Solving with semaphores We’ll use two kinds of semaphores We’ll use counters to track how much data is in the buffer One counter counts as we add data and stops the producer if there are N objects in the buffer A second counter counts as we remove data and stops a consumer if there are 0 in the buffer Idea: since general semaphores can count for us, we don’t need a separate counter variable Why do we need a second kind of semaphore? We’ll also need a mutex semaphore
  • 12. Shared: Semaphores mutex, empty, full; Init: mutex = 1; /* for mutual exclusion*/ empty = N; /* number empty buf entries */ full = 0; /* number full buf entries */ Producer do { . . . // produce an item in nextp . . . P(empty); P(mutex); . . . // add nextp to buffer . . . V(mutex); V(full); } while (true); Consumer do { P(full); P(mutex); . . . // remove item to nextc . . . V(mutex); V(empty); . . . // consume item in nextc . . . } while (true);
  • 13. Monitor: object with a set of monitor procedures and only one thread may be active (i.e. running one of the monitor procedures) at a time
  • 14. Compiler automatically inserts lock and unlock operations upon entry and exit of monitor procedures
  • 15. Two condition variables has_empty: buffer has at least one empty slot has_full: buffer has at least one full slot nfull: number of filled slots Need to do our own counting for condition variables
  • 16.
  • 17. Semaphores are sticky: they have memory, sem_post() will increment the semaphore counter, even if no one has called sem_wait() Condition variables are not: if no one is waiting for a signal(), this signal() is not saved  Despite the difference, they are as powerful
  • 18. Wait(s) and signal(s) are scattered among several processes therefore it is difficult to understand their effect. Usage must be correct in all the processes. One bad process or one program error can kill the whole system.
  • 20. A data set is shared among a number of concurrent processes Readers – only read the data set; they do not perform any updates Writers – can both read and write. Many threads share an object in memory Some write to it, some only read it Only one writer can be active at a time Any number of readers can be active simultaneously
  • 21. One issue we need to settle, to clarify problem statement. Suppose that a writer is active and a mixture of readers and writers now shows up. Who should get in next? Or suppose that a writer is waiting and an endless of stream of readers keeps showing up. Is it fair for them to become active? We’ll favor a kind of back-and-forth form of fairness: Once a reader is waiting, readers will get in next. If a writer is waiting, one writer will get in next.
  • 22. Example: making an airline reservation  When you browse to look at flight schedules the web site is acting as a reader on your behalf  When you reserve a seat, the web site has to write into the database to make the reservation  a web server cache needs to quickly serve the same static page for many thousands of requests. Occasionally however an author may decide to update the page.
  • 23. The structure of a Readers-writers process using mutex: Shared variables: Semaphore mutex, wrl; integer rcount; Init: mutex = 1, wrl = 1, rcount = 0; Writer do { P(wrl); . . . /*writing is performed*/ . . . V(wrl); }while(TRUE); Reader do { P(wrl); . . . /*Reading is performed*/ . . . V(wrl); }while(TRUE);
  • 24. The structure of a reader process using semaphore: do { P(mutex); rcount++; if (rcount == 1) P(wrl); V(mutex); . . . /*reading is performed*/ . . . P(mutex); rcount--; if (rcount == 0) V(wrl); V(mutex); }while(TRUE);
  • 25. If there is a writer  First reader blocks on wrl  Other readers block on mutex Once a reader is active, all readers get to go through  Trick question: Which reader gets in first? The last reader to exit signals a writer  If no writer, then readers can continue If readers and writers waiting on wrl, and writer exits  Who gets to go in first? Why doesn’t a writer need to use mutex?
  • 26. Why doesn’t a writer need to use mutex?
  • 27. If readers are active, no writer can enter The writers wait doing a P(wrl) While writer is active, nobody can enter Any other reader or writer will wait But back-and-forth switching is buggy: Any number of readers can enter in a row Readers can “starve” writers With semaphores, building a solution that has the desired back-and-forth behavior is really, really tricky! We recommend that you try, but not too hard…
  • 28. readers-writers : monitor; begin readercount : integer; busy : boolean; OKtoread, OKtowrite : condition; procedure startread; Begin if busy then OKtoread.wait; readercount := readercount + 1; OKtoread.signal; (* Once one reader can start, they all can *) end startread; procedure endread; begin readercount := readercount - 1; if readercount = 0 then OKtowrite.signal; end endread;
  • 29. procedure startwrite; begin if busy OR readercount != 0 then OKtowrite.wait; busy := true; end startwrite; procedure endwrite; begin busy := false; if OKtoread.queue then OKtoread.signal else OKtowrite.signal; end endwrite; begin (* initialization *) readercount := 0; busy := false; end; end readers-writers;
  • 30. For proper sychronization, reader processes must call the startread procedure before accessing the file (shared resource) and call the endread when the read is finished. Likewise, writer processes must call startwrite before modifying the file and call endwrite when the write is finished. The monitor uses the boolean variable busy to indicate whether a writer is active (i.e., accessing the file) and readercount to keep track of the number of active readers.
  • 31. A writer, on invoking startwrite, proceeds only when no other writer or readers are active.  In summary, the reader's priority monitor, while not permitting a new writer to start when there is a reader waiting, permits any number of readers to proceed, as long as there is at least one active reader.