ITPub博客

首页 > > > python consumer producer

python consumer producer

作者:友哥 时间:2018-04-27 11:23:00 0 删除 编辑
from threading import Thread, Lock
import time
import random

queue = []
lock = Lock()

class ProducerThread(Thread):
    def run(self):
        nums = range(5) #Will create the list [0, 1, 2, 3, 4]
        global queue
        while True:
            num = random.choice(nums) #Selects a random number from list [0, 1, 2, 3, 4]
            lock.acquire()
            queue.append(num)
            print "Produced", num
            lock.release()
            time.sleep(random.random())


class ConsumerThread(Thread):
    def run(self):
        global queue
        while True:
            lock.acquire()
            if not queue:
                print "Nothing in queue, but consumer will try to consume"

            if len(queue) > 0:
                num = queue.pop(0)
                print "Consumed", num
            lock.release()
            time.sleep(random.random())


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

 

原文作者:;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2020-05-20

  • 博文量
    276
  • 访问量
    999