SlideShare a Scribd company logo
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  }  }

More Related Content

What's hot

Page replacement algorithms
Page replacement algorithmsPage replacement algorithms
Page replacement algorithms
Piyush Rochwani
 
Semaphore
SemaphoreSemaphore
Semaphore
Arafat Hossan
 
Bankers algorithm
Bankers algorithmBankers algorithm
Bankers algorithm
AAQIB PARREY
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
Syed Hassan Ali
 
Operating system 25 classical problems of synchronization
Operating system 25 classical problems of synchronizationOperating system 25 classical problems of synchronization
Operating system 25 classical problems of synchronization
Vaibhav Khanna
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's types
Nishant Joshi
 
contiguous memory allocation.pptx
contiguous memory allocation.pptxcontiguous memory allocation.pptx
contiguous memory allocation.pptx
Rajapriya82
 
Queue ppt
Queue pptQueue ppt
Queue ppt
SouravKumar328
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem Solution
Bipul Chandra Kar
 
Free Space Management, Efficiency & Performance, Recovery and NFS
Free Space Management, Efficiency & Performance, Recovery and NFSFree Space Management, Efficiency & Performance, Recovery and NFS
Free Space Management, Efficiency & Performance, Recovery and NFS
United International University
 
Operating system critical section
Operating system   critical sectionOperating system   critical section
Operating system critical section
Harshana Madusanka Jayamaha
 
Semaphores
SemaphoresSemaphores
Semaphores
Mohd Arif
 
Shared memory
Shared memoryShared memory
Shared memory
Abhishek Khune
 
Fragmentaton
Fragmentaton Fragmentaton
Fragmentaton
sanjana mun
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
swapnac12
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
myrajendra
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 
Memory management
Memory managementMemory management
Memory management
cpjcollege
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 

What's hot (20)

Page replacement algorithms
Page replacement algorithmsPage replacement algorithms
Page replacement algorithms
 
Semaphore
SemaphoreSemaphore
Semaphore
 
Bankers algorithm
Bankers algorithmBankers algorithm
Bankers algorithm
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
 
Operating system 25 classical problems of synchronization
Operating system 25 classical problems of synchronizationOperating system 25 classical problems of synchronization
Operating system 25 classical problems of synchronization
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's types
 
contiguous memory allocation.pptx
contiguous memory allocation.pptxcontiguous memory allocation.pptx
contiguous memory allocation.pptx
 
Queue ppt
Queue pptQueue ppt
Queue ppt
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem Solution
 
Free Space Management, Efficiency & Performance, Recovery and NFS
Free Space Management, Efficiency & Performance, Recovery and NFSFree Space Management, Efficiency & Performance, Recovery and NFS
Free Space Management, Efficiency & Performance, Recovery and NFS
 
Operating system critical section
Operating system   critical sectionOperating system   critical section
Operating system critical section
 
Semaphores
SemaphoresSemaphores
Semaphores
 
Shared memory
Shared memoryShared memory
Shared memory
 
Fragmentaton
Fragmentaton Fragmentaton
Fragmentaton
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
Inter threadcommunication.38
Inter threadcommunication.38Inter threadcommunication.38
Inter threadcommunication.38
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
Memory management
Memory managementMemory management
Memory management
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 

Viewers also liked

Producer and consumer classical problem
Producer and consumer classical problemProducer and consumer classical problem
Producer and consumer classical problem
latechwizard
 
Producer Consumer
Producer ConsumerProducer Consumer
Producer Consumer
Muteeb Kamboh
 
Dining Philosopher's Problem
Dining Philosopher's ProblemDining Philosopher's Problem
Dining Philosopher's Problem
Yash Mittal
 
Semaphores OS Basics
Semaphores OS BasicsSemaphores OS Basics
Semaphores OS Basics
Shijin Raj P
 
OS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and MonitorsOS Process Synchronization, semaphore and Monitors
OS Process Synchronization, semaphore and Monitors
sgpraju
 
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
 
The bounded buffer
The bounded bufferThe bounded buffer
The bounded buffer
Bhuridech Sudsee
 
DPP
DPPDPP
Semaphore
SemaphoreSemaphore
Semaphore
naniix21_3
 
Lec11 semaphores
Lec11 semaphoresLec11 semaphores
Lec11 semaphores
anandammca
 
Interrupts
InterruptsInterrupts
Interrupts
guest2e9811e
 
Operating System Deadlock Galvin
Operating System  Deadlock GalvinOperating System  Deadlock Galvin
Operating System Deadlock Galvin
Sonali Chauhan
 
Memory management
Memory managementMemory management
Memory management
Rajni Sirohi
 
Process synchronization in operating system
Process synchronization in operating systemProcess synchronization in operating system
Process synchronization in operating system
Ruaha Catholic university
 
Process synchronization(deepa)
Process synchronization(deepa)Process synchronization(deepa)
Process synchronization(deepa)
Nagarajan
 
Producers and Consumers
Producers and ConsumersProducers and Consumers
Producers and Consumers
drpnknwlg
 
deadlock avoidance
deadlock avoidancedeadlock avoidance
deadlock avoidance
wahab13
 
Operating Systems - Synchronization
Operating Systems - SynchronizationOperating Systems - Synchronization
Operating Systems - Synchronization
Emery Berger
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
Sonali Chauhan
 

Viewers also liked (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
 
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
 
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
 
deadlock avoidance
deadlock avoidancedeadlock avoidance
deadlock avoidance
 
Operating Systems - Synchronization
Operating Systems - SynchronizationOperating Systems - Synchronization
Operating Systems - Synchronization
 
Process Synchronization
Process SynchronizationProcess Synchronization
Process Synchronization
 

Similar to Producer consumer

Producer sonsumer ppt
Producer sonsumer pptProducer sonsumer ppt
Producer sonsumer ppt
Ayesha Siddiqua
 
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
 
UNIT III Process Synchronization.docx
UNIT III Process Synchronization.docxUNIT III Process Synchronization.docx
UNIT III Process Synchronization.docx
karthikaparthasarath
 
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
 
Producer consumer.docx
Producer consumer.docxProducer consumer.docx
Producer consumer.docx
Abhishek361641
 
Teorical1
Teorical1Teorical1
Teorical1
Ever Blut
 
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
 
Reactive programming with tracker
Reactive programming with trackerReactive programming with tracker
Reactive programming with tracker
Designveloper
 
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
 
Classic synchronization
Classic synchronizationClassic synchronization
Classic synchronization
hina firdaus
 
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
 
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
Gowtham Reddy
 
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
 

Similar to Producer consumer (20)

Producer sonsumer ppt
Producer sonsumer pptProducer sonsumer ppt
Producer sonsumer ppt
 
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
 

More from Mohd Tousif

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

More from 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.
 

Recently uploaded

Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
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
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
NgcHiNguyn25
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
Israel Genealogy Research Association
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
Kavitha Krishnan
 
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
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 

Recently uploaded (20)

Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.Types of Herbal Cosmetics its standardization.
Types of Herbal Cosmetics its standardization.
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
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
 
Life upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for studentLife upper-Intermediate B2 Workbook for student
Life upper-Intermediate B2 Workbook for student
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
The Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collectionThe Diamonds of 2023-2024 in the IGRA collection
The Diamonds of 2023-2024 in the IGRA collection
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Assessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptxAssessment and Planning in Educational technology.pptx
Assessment and Planning in Educational technology.pptx
 
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...
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 

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 } }