SlideShare a Scribd company logo
1 of 32
• 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 & answersMd. Mashiur Rahman
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's typesNishant Joshi
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationWayne 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.docxstilliegeorgiana
 
Process Synchronization -1.ppt
Process Synchronization -1.pptProcess Synchronization -1.ppt
Process Synchronization -1.pptjayverma27
 
10 Multicore 07
10 Multicore 0710 Multicore 07
10 Multicore 07timcrack
 
Classical problems of process synchronization
Classical problems of process synchronizationClassical problems of process synchronization
Classical problems of process synchronizationsangrampatil81
 
readerwriter-190410082551.pdf
readerwriter-190410082551.pdfreaderwriter-190410082551.pdf
readerwriter-190410082551.pdfRohanThota3
 
Reader/writer problem
Reader/writer problemReader/writer problem
Reader/writer problemRinkuMonani
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10Minal Maniar
 
Reactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaReactive java - Reactive Programming + RxJava
Reactive java - Reactive Programming + RxJavaNexThoughts Technologies
 
Types or evolution of operating system
Types or evolution of operating systemTypes or evolution of operating system
Types or evolution of operating systemEkta Bafna
 

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

MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

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.