Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

producer consumer problem using queue python

from threading import Thread, Condition
import time
import random

queue = []
MAX_NUM = 10
condition = Condition()

class ProducerThread(Thread):
    def run(self):
        nums = range(5)
        global queue
        while True:
            condition.acquire()
            if len(queue) == MAX_NUM:
                print "Queue full, producer is waiting"
                condition.wait()
                print "Space in queue, Consumer notified the producer"
            num = random.choice(nums)
            queue.append(num)
            print "Produced", num
            condition.notify()
            condition.release()
            time.sleep(random.random())


class ConsumerThread(Thread):
    def run(self):
        global queue
        while True:
            condition.acquire()
            if not queue:
                print "Nothing in queue, consumer is waiting"
                condition.wait()
                print "Producer added something to queue and notified the consumer"
            num = queue.pop(0)
            print "Consumed", num
            condition.notify()
            condition.release()
            time.sleep(random.random())


ProducerThread().start()
ConsumerThread().start()
Comment

PREVIOUS NEXT
Code Example
Python :: change the style of notebook tkinter 
Python :: exact distance math 
Python :: find common words in two lists python 
Python :: word pattern in python 
Python :: list to string python 
Python :: random variables python 
Python :: euclidean distance python 
Python :: how do I run a python program on atom 
Python :: python random phone number 
Python :: average out all rows pandas 
Python :: cv2.adaptiveThreshold() 
Python :: django message framework 
Python :: pyspark select without column 
Python :: pandas describe get mean min max 
Python :: how to merge dataframe with different keys 
Python :: python list minus list 
Python :: for each value in column pandas 
Python :: python turn 0 into 1 and vice versa 
Python :: how to change web browser in python 
Python :: pandas count distinct 
Python :: check if coroutine python 
Python :: django foreign key error Cannot assign must be a instance 
Python :: python get html info 
Python :: create pdf from images python 
Python :: django.core.exceptions.FieldError: Unknown field(s) (author) specified for Comment 
Python :: matplotlib create histogram edge color 
Python :: reduce in python 
Python :: How can one find the three largest values of an input array efficiently, namely without having to sort the input array? 
Python :: pytorch save model 
Python :: how to find columns of a dataframe 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =