Python3

Producer & Consumer

2018-10-12  本文已影响6人  JaedenKil
from threading import Thread, Condition
import time
import random

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


class ProducerThread(Thread):
    def run(self):
        nums = range(666666)
        global queue
        while True:
            condition.acquire()
            if len(queue) == MAX_NUM:
                print "The queue is full, the producer is waiting."
                condition.wait()
                print "There is space is the queue, the consumer notified the producer."
            num = random.choice(nums)  # Select a random number from the list
            nums.remove(num)
            queue.append(num)
            print "Produce %d." % num
            condition.notify()
            condition.release()
            time.sleep(random.random() * 3)


class ConsumerThread(Thread):
    def run(self):
        global queue
        while True:
            condition.acquire()
            if not queue:
                print "The queue is empty, consumer is waiting."
                condition.wait()
                print "The producer added an element to the queue and notified the consumer."
            num = queue.pop(0)
            print "Consume %d." % num
            condition.notify()
            condition.release()
            time.sleep(random.random() * 3)


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

from threading import Thread
import time
import random
from Queue import Queue


queue = Queue(10)


class ProducerThread(Thread):
    def run(self):
        nums = range(2)
        global queue
        while True:
            num = random.choice(nums)
            queue.put(num)
            print "Produce %d" % num
            time.sleep(random.random())


class ConsumerThread(Thread):
    def run(self):
        global queue
        while True:
            num = queue.get()
            queue.task_done()
            print "Consume %d" %num
            time.sleep(random.random())


ProducerThread().start()
ConsumerThread().start()
上一篇下一篇

猜你喜欢

热点阅读