Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

producer and consumer problem in python

import threading
import time
 
# Shared Memory variables
CAPACITY = 10
buffer = [-1 for i in range(CAPACITY)]
in_index = 0
out_index = 0
 
# Declaring Semaphores
mutex = threading.Semaphore()
empty = threading.Semaphore(CAPACITY)
full = threading.Semaphore(0)
 
# Producer Thread Class
class Producer(threading.Thread):
  def run(self):
     
    global CAPACITY, buffer, in_index, out_index
    global mutex, empty, full
     
    items_produced = 0
    counter = 0
     
    while items_produced < 20:
      empty.acquire()
      mutex.acquire()
       
      counter += 1
      buffer[in_index] = counter
      in_index = (in_index + 1)%CAPACITY
      print("Producer produced : ", counter)
       
      mutex.release()
      full.release()
       
      time.sleep(1)
       
      items_produced += 1
 
# Consumer Thread Class
class Consumer(threading.Thread):
  def run(self):
     
    global CAPACITY, buffer, in_index, out_index, counter
    global mutex, empty, full
     
    items_consumed = 0
     
    while items_consumed < 20:
      full.acquire()
      mutex.acquire()
       
      item = buffer[out_index]
      out_index = (out_index + 1)%CAPACITY
      print("Consumer consumed item : ", item)
       
      mutex.release()
      empty.release()      
       
      time.sleep(2.5)
       
      items_consumed += 1
 
# Creating Threads
producer = Producer()
consumer = Consumer()
 
# Starting Threads
consumer.start()
producer.start()
 
# Waiting for threads to complete
producer.join()
consumer.join()
Comment

PREVIOUS NEXT
Code Example
Python :: python empty dataframe 
Python :: inpuit inf terfminal ppython 
Python :: list of lists to table python 
Python :: python seaborn violin plot 
Python :: stack program in python3 
Python :: Using Lists as Queues 
Python :: matplotlib default style 
Python :: sorting decimal numbers in python 
Python :: python 
Python :: create_polygon tkinter 
Python :: rename a file in python 
Python :: tkinter tutorial 
Python :: move files in python 
Python :: count elements in list python 
Python :: remove trailing zeros python 
Python :: relative text size put text cv2 
Python :: python does string contain space 
Python :: np.array([(1,2),(3,4)],dtype 
Python :: python if boolean logic 
Python :: add item to tuple python 
Python :: pandas filter column greater than 
Python :: how to take a list as input in python using sys.srgv 
Python :: python3 tuple 
Python :: np.vectorize 
Python :: get lastest files from directory python 
Python :: counter library python 
Python :: how to get data after last slash in python 
Python :: how to tell python to go back to a previous line 
Python :: PHP echo multi lines Using Nowdoc variable 
Python :: python googledriver download 
ADD CONTENT
Topic
Content
Source link
Name
8+3 =