SlideShare ist ein Scribd-Unternehmen logo
1 von 18
PRODUCER-CONSUMER  PROBLEM BY: MOHD TOUSIF & MOHD MOHSIN
OVERVIEW  producer-consumer problem (also known as the bounded-buffer problem) is a multi-process synchronization problem.  The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer. Producer  :- The producer's job is to generate a piece of data, put it into the buffer and start again. Consumer :- The consumer is consuming the data (i.e., removing it from the buffer) one piece at a time. 
PROBLEM The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.
Solution for the producer ,[object Object]
The next time the consumer removes an item from the buffer and it notifies the producer who starts to fill the buffer again.,[object Object]
 The next time the producer puts data into the buffer, it wakes up the sleeping consumer.,[object Object]
CONSUMER
INADEQUATE SOLUTION BufferSize = 3;  count = 0; Producer()  {  int item;  WHILE (true)  {                        make_new(item);                                // create a new item to put in the buffer  IF(count==BufferSize)  Sleep();                                           // if the buffer is full, sleep  put_item(item);                            // put the item in the buffer  count = count + 1;                         // increment count of items  IF (count==1)  Wakeup(Consumer);                    // if the buffer was previously empty, wake the consumer  }                                                  }
INADEQUATE SOLUTION  Consumer()  {  Int item;  WHILE(true)  {                                        IF(count==0)  Sleep();                                                     // if the buffer is empty, sleep  remove_item(item);                               // take an item from the buffer  count = count - 1;                                  // decrement count of items  IF(count==N-1)  Wakeup(Producer);                              // if buffer was previously full, wake the producer  Consume_item(item);                           // consume the item  }  }
Problem with the above Solution The problem with this solution is that it contains a race condition that can lead into a deadlock. Consider the following scenario: The consumer has just read the variable itemCount, noticed it's zero and is just about to move inside the if-block. Just before calling sleep, the consumer is interrupted and the producer is resumed. The producer creates an item, puts it into the buffer, and increases itemCount. Because the buffer was empty prior to the last addition, the producer tries to wake up the consumer. Unfortunately the consumer wasn't yet sleeping, and the wakeup call is lost. When the consumer resumes, it goes to sleep and will never be awakened again. This is because the consumer is only awakened by the producer when itemCount is equal to 1. The producer will loop until the buffer is full, after which it will also go to sleep. Since both processes will sleep forever, we have run into a deadlock. This solution therefore is unsatisfactory.
Solution using Semaphore BufferSize = 3; semaphore mutex = 1;                                // Controls access to critical section semaphore empty = BufferSize;                 // counts number of empty buffer slots semaphore full = 0;                                 // counts number of full buffer slots  Producer()  {  intitem;  while (TRUE)  {              make_new(item);                       // create a new item to put in the buffer  down(∅);                                      // decrement the empty semaphore  down(&mutex);                           // enter critical section  put_item(item);                     // put item in buffer  up(&mutex);                           // leave critical section  up(&full);                             // increment the full semaphore  }  }
Solution using Semaphore Consumer()  {  int  item; while (TRUE)  {        down(&full);                            // decrement the full semaphore   down(&mutex);                       // enter critical section remove_item(item);            // take a item from the buffer  up(&mutex);                        // leave critical section  up(∅);                               // increment the empty semaphore consume_item(item);      // consume the item  }  }
Solution using Semaphore In the above example there are three semaphores. ,[object Object]
empty, used for counting the number of slots that are empty;
mutex, used to enforce mutual exclusion.,[object Object]
Solution using Monitors monitorProducerConsumer condition full, empty;  int count;  procedure enter();  {  if (count == N)  wait(full);                  // if buffer is full, block put_item(item);    // put item in buffer  count = count + 1;                    // increment count of full slots  if (count == 1)   signal(empty);                               // if buffer was empty,  wake consumer  }
Solution using Monitors procedure remove();  {  if (count == 0) wait(empty);         // if buffer is empty, block  remove_item(item);                    // remove item from buffer  count = count - 1;                     // decrement count of full slots  if (count == N-1)  signal(full);                             // if buffer was full,  wake producer  }  count = 0; end monitor;
Solution using Monitors Producer();  {  while (TRUE)  {  make_item(item);            // make a new item  ProducerConsumer.enter;    // call enter function in monitor  }  }

Weitere ähnliche Inhalte

Was ist angesagt?

Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
Ravindra Raju Kolahalam
 
Operating system services 9
Operating system services 9Operating system services 9
Operating system services 9
myrajendra
 

Was ist angesagt? (20)

Methods for handling deadlocks
Methods for handling deadlocksMethods for handling deadlocks
Methods for handling deadlocks
 
Paging and segmentation
Paging and segmentationPaging and segmentation
Paging and segmentation
 
File system structure
File system structureFile system structure
File system structure
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
BANKER'S ALGORITHM
BANKER'S ALGORITHMBANKER'S ALGORITHM
BANKER'S ALGORITHM
 
INTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxINTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptx
 
Critical Section in Operating System
Critical Section in Operating SystemCritical Section in Operating System
Critical Section in Operating System
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
 
Multiprocessor
MultiprocessorMultiprocessor
Multiprocessor
 
Deadlock in Distributed Systems
Deadlock in Distributed SystemsDeadlock in Distributed Systems
Deadlock in Distributed Systems
 
Cache memory
Cache memoryCache memory
Cache memory
 
Bankers algorithm
Bankers algorithmBankers algorithm
Bankers algorithm
 
Operating system services 9
Operating system services 9Operating system services 9
Operating system services 9
 
Virtual memory ppt
Virtual memory pptVirtual memory ppt
Virtual memory ppt
 
Computer arithmetic
Computer arithmeticComputer arithmetic
Computer arithmetic
 
Computer architecture multi processor
Computer architecture multi processorComputer architecture multi processor
Computer architecture multi processor
 
Scheduling Definition, objectives and types
Scheduling Definition, objectives and types Scheduling Definition, objectives and types
Scheduling Definition, objectives and types
 
Synchronization hardware
Synchronization hardwareSynchronization hardware
Synchronization hardware
 
Chapter 7 - Deadlocks
Chapter 7 - DeadlocksChapter 7 - Deadlocks
Chapter 7 - Deadlocks
 
Elements of cache design
Elements of cache designElements of cache design
Elements of cache design
 

Andere mochten auch

Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
Wayne Jones Jnr
 
Ch7 OS
Ch7 OSCh7 OS
Ch7 OS
C.U
 
Lec11 semaphores
Lec11 semaphoresLec11 semaphores
Lec11 semaphores
anandammca
 
Operating System Deadlock Galvin
Operating System  Deadlock GalvinOperating System  Deadlock Galvin
Operating System Deadlock Galvin
Sonali Chauhan
 
Process synchronization(deepa)
Process synchronization(deepa)Process synchronization(deepa)
Process synchronization(deepa)
Nagarajan
 

Andere mochten auch (20)

Producer and consumer classical problem
Producer and consumer classical problemProducer and consumer classical problem
Producer and consumer classical problem
 
Producer Consumer
Producer ConsumerProducer Consumer
Producer Consumer
 
Semaphores
SemaphoresSemaphores
Semaphores
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem Solution
 
Dining Philosopher's Problem
Dining Philosopher's ProblemDining Philosopher's Problem
Dining Philosopher's Problem
 
Semaphores OS Basics
Semaphores OS BasicsSemaphores OS Basics
Semaphores OS Basics
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitors
 
Chapter 6 - Process Synchronization
Chapter 6 - Process SynchronizationChapter 6 - Process Synchronization
Chapter 6 - Process Synchronization
 
Operating system critical section
Operating system   critical sectionOperating system   critical section
Operating system critical section
 
Ch7 OS
Ch7 OSCh7 OS
Ch7 OS
 
The bounded buffer
The bounded bufferThe bounded buffer
The bounded buffer
 
DPP
DPPDPP
DPP
 
Semaphore
SemaphoreSemaphore
Semaphore
 
Lec11 semaphores
Lec11 semaphoresLec11 semaphores
Lec11 semaphores
 
Interrupts
InterruptsInterrupts
Interrupts
 
Operating System Deadlock Galvin
Operating System  Deadlock GalvinOperating System  Deadlock Galvin
Operating System Deadlock Galvin
 
Memory management
Memory managementMemory management
Memory management
 
Process synchronization in operating system
Process synchronization in operating systemProcess synchronization in operating system
Process synchronization in operating system
 
Process synchronization(deepa)
Process synchronization(deepa)Process synchronization(deepa)
Process synchronization(deepa)
 
Producers and Consumers
Producers and ConsumersProducers and Consumers
Producers and Consumers
 

Ähnlich wie Producer consumer

Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4
Neeraj Kaushik
 
this file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdfthis file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdf
flashfashioncasualwe
 
This file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdfThis file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdf
deepaksatrker
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
fashiongallery1
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdf
deepaarora22
 
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdfListings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf
RAJATCHUGH12
 
OverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docxOverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docx
alfred4lewis58146
 
Hello need help on this lab- what you need to do is add a code to Arra.pdf
Hello need help on this lab- what you need to do is add a code to Arra.pdfHello need help on this lab- what you need to do is add a code to Arra.pdf
Hello need help on this lab- what you need to do is add a code to Arra.pdf
Ian0J2Bondo
 
Use a simple vector you created before to create two other more
Use a simple vector you created before to create two other more Use a simple vector you created before to create two other more
Use a simple vector you created before to create two other more
steviesellars
 
Process Synchronization Producer-Consumer ProblemThe purpose o.docx
Process Synchronization Producer-Consumer ProblemThe purpose o.docxProcess Synchronization Producer-Consumer ProblemThe purpose o.docx
Process Synchronization Producer-Consumer ProblemThe purpose o.docx
stilliegeorgiana
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
eyebolloptics
 
all i need is these two filesCreate VectorContainer.hppCreat.docx
all i need is these two filesCreate VectorContainer.hppCreat.docxall i need is these two filesCreate VectorContainer.hppCreat.docx
all i need is these two filesCreate VectorContainer.hppCreat.docx
jack60216
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
sktambifortune
 
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
 

Ähnlich wie Producer consumer (20)

Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4Concurrent Collections Object In Dot Net 4
Concurrent Collections Object In Dot Net 4
 
UNIT III Process Synchronization.docx
UNIT III Process Synchronization.docxUNIT III Process Synchronization.docx
UNIT III Process Synchronization.docx
 
this file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdfthis file has a complete array-based MultiSet, but not the code need.pdf
this file has a complete array-based MultiSet, but not the code need.pdf
 
This file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdfThis file contains a complete array-based MultiSet, but not the code.pdf
This file contains a complete array-based MultiSet, but not the code.pdf
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
 
Producer consumer.docx
Producer consumer.docxProducer consumer.docx
Producer consumer.docx
 
Teorical1
Teorical1Teorical1
Teorical1
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdf
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
 
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdfListings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf
Listings for BinaryHeap.java and BinaryHeapTest.java are shown in th.pdf
 
OverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docxOverviewUsing the C-struct feature, design, implement and .docx
OverviewUsing the C-struct feature, design, implement and .docx
 
Classic synchronization
Classic synchronizationClassic synchronization
Classic synchronization
 
Hello need help on this lab- what you need to do is add a code to Arra.pdf
Hello need help on this lab- what you need to do is add a code to Arra.pdfHello need help on this lab- what you need to do is add a code to Arra.pdf
Hello need help on this lab- what you need to do is add a code to Arra.pdf
 
Implementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphoresImplementing of classical synchronization problem by using semaphores
Implementing of classical synchronization problem by using semaphores
 
Use a simple vector you created before to create two other more
Use a simple vector you created before to create two other more Use a simple vector you created before to create two other more
Use a simple vector you created before to create two other more
 
Process Synchronization Producer-Consumer ProblemThe purpose o.docx
Process Synchronization Producer-Consumer ProblemThe purpose o.docxProcess Synchronization Producer-Consumer ProblemThe purpose o.docx
Process Synchronization Producer-Consumer ProblemThe purpose o.docx
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
 
all i need is these two filesCreate VectorContainer.hppCreat.docx
all i need is these two filesCreate VectorContainer.hppCreat.docxall i need is these two filesCreate VectorContainer.hppCreat.docx
all i need is these two filesCreate VectorContainer.hppCreat.docx
 
Create a Dynamic Array container with this user interface Ge.pdf
Create a Dynamic Array container with this user interface  Ge.pdfCreate a Dynamic Array container with this user interface  Ge.pdf
Create a Dynamic Array container with this user interface Ge.pdf
 
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
 

Mehr von Mohd Tousif

Mehr von Mohd Tousif (20)

Sql commands
Sql commandsSql commands
Sql commands
 
Sql basics and DDL statements
Sql basics and DDL statementsSql basics and DDL statements
Sql basics and DDL statements
 
SQL practice questions set
SQL practice questions setSQL practice questions set
SQL practice questions set
 
Introduction to Databases
Introduction to DatabasesIntroduction to Databases
Introduction to Databases
 
Entity Relationship Model - An Example
Entity Relationship Model - An ExampleEntity Relationship Model - An Example
Entity Relationship Model - An Example
 
Entity Relationship (ER) Model Questions
Entity Relationship (ER) Model QuestionsEntity Relationship (ER) Model Questions
Entity Relationship (ER) Model Questions
 
Entity Relationship (ER) Model
Entity Relationship (ER) ModelEntity Relationship (ER) Model
Entity Relationship (ER) Model
 
SQL Practice Question set
SQL Practice Question set SQL Practice Question set
SQL Practice Question set
 
Introduction to Databases - Assignment_1
Introduction to Databases - Assignment_1Introduction to Databases - Assignment_1
Introduction to Databases - Assignment_1
 
Data Definition Language (DDL)
Data Definition Language (DDL) Data Definition Language (DDL)
Data Definition Language (DDL)
 
Data Warehouse Concepts and Architecture
Data Warehouse Concepts and ArchitectureData Warehouse Concepts and Architecture
Data Warehouse Concepts and Architecture
 
SQL practice questions set - 2
SQL practice questions set - 2SQL practice questions set - 2
SQL practice questions set - 2
 
SQL practice questions - set 3
SQL practice questions - set 3SQL practice questions - set 3
SQL practice questions - set 3
 
SQL practice questions for beginners
SQL practice questions for beginnersSQL practice questions for beginners
SQL practice questions for beginners
 
Oracle sql tutorial
Oracle sql tutorialOracle sql tutorial
Oracle sql tutorial
 
Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)Sql (Introduction to Structured Query language)
Sql (Introduction to Structured Query language)
 
Sql commands
Sql commandsSql commands
Sql commands
 
Virtual box
Virtual boxVirtual box
Virtual box
 
Deadlock
DeadlockDeadlock
Deadlock
 
Algorithm o.s.
Algorithm o.s.Algorithm o.s.
Algorithm o.s.
 

Kürzlich hochgeladen

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Kürzlich hochgeladen (20)

HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 

Producer consumer

  • 1. PRODUCER-CONSUMER PROBLEM BY: MOHD TOUSIF & MOHD MOHSIN
  • 2. OVERVIEW  producer-consumer problem (also known as the bounded-buffer problem) is a multi-process synchronization problem.  The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer. Producer :- The producer's job is to generate a piece of data, put it into the buffer and start again. Consumer :- The consumer is consuming the data (i.e., removing it from the buffer) one piece at a time. 
  • 3. PROBLEM The problem is to make sure that the producer won't try to add data into the buffer if it's full and that the consumer won't try to remove data from an empty buffer.
  • 4.
  • 5.
  • 6.
  • 8. INADEQUATE SOLUTION BufferSize = 3; count = 0; Producer() { int item; WHILE (true) { make_new(item); // create a new item to put in the buffer IF(count==BufferSize) Sleep(); // if the buffer is full, sleep put_item(item); // put the item in the buffer count = count + 1; // increment count of items IF (count==1) Wakeup(Consumer); // if the buffer was previously empty, wake the consumer } }
  • 9. INADEQUATE SOLUTION Consumer() { Int item; WHILE(true) { IF(count==0) Sleep(); // if the buffer is empty, sleep remove_item(item); // take an item from the buffer count = count - 1; // decrement count of items IF(count==N-1) Wakeup(Producer); // if buffer was previously full, wake the producer Consume_item(item); // consume the item } }
  • 10. Problem with the above Solution The problem with this solution is that it contains a race condition that can lead into a deadlock. Consider the following scenario: The consumer has just read the variable itemCount, noticed it's zero and is just about to move inside the if-block. Just before calling sleep, the consumer is interrupted and the producer is resumed. The producer creates an item, puts it into the buffer, and increases itemCount. Because the buffer was empty prior to the last addition, the producer tries to wake up the consumer. Unfortunately the consumer wasn't yet sleeping, and the wakeup call is lost. When the consumer resumes, it goes to sleep and will never be awakened again. This is because the consumer is only awakened by the producer when itemCount is equal to 1. The producer will loop until the buffer is full, after which it will also go to sleep. Since both processes will sleep forever, we have run into a deadlock. This solution therefore is unsatisfactory.
  • 11. Solution using Semaphore BufferSize = 3; semaphore mutex = 1; // Controls access to critical section semaphore empty = BufferSize; // counts number of empty buffer slots semaphore full = 0; // counts number of full buffer slots Producer() { intitem; while (TRUE) { make_new(item); // create a new item to put in the buffer down(∅); // decrement the empty semaphore down(&mutex); // enter critical section put_item(item); // put item in buffer up(&mutex); // leave critical section up(&full); // increment the full semaphore } }
  • 12. Solution using Semaphore Consumer() { int item; while (TRUE) { down(&full); // decrement the full semaphore down(&mutex); // enter critical section remove_item(item); // take a item from the buffer up(&mutex); // leave critical section up(∅); // increment the empty semaphore consume_item(item); // consume the item } }
  • 13.
  • 14. empty, used for counting the number of slots that are empty;
  • 15.
  • 16. Solution using Monitors monitorProducerConsumer condition full, empty; int count; procedure enter(); { if (count == N) wait(full); // if buffer is full, block put_item(item); // put item in buffer count = count + 1; // increment count of full slots if (count == 1) signal(empty); // if buffer was empty, wake consumer }
  • 17. Solution using Monitors procedure remove(); { if (count == 0) wait(empty); // if buffer is empty, block remove_item(item); // remove item from buffer count = count - 1; // decrement count of full slots if (count == N-1) signal(full); // if buffer was full, wake producer } count = 0; end monitor;
  • 18. Solution using Monitors Producer(); { while (TRUE) { make_item(item); // make a new item ProducerConsumer.enter; // call enter function in monitor } }
  • 19. Solution using Monitors Consumer(); { while (TRUE) { ProducerConsumer.remove; // call remove function in monitor consume_item; // consume an item } }