生产者-消费者模型-线程安全队列Queue

时间:2022-09-20 17:40:51

简单案例:

#!/usr/bin/python
import time, threading,Queue
#class to do sth
class Comsumer(threading.Thread):
def __init__(self,queue):
  threading.Thread.__init__(self)
  self.queue = queue
def run(self):
  while True:
    msg = self.queue.get()
    if msg == 'quit':
      break
    print 'msg is : {0}'.format(msg)
    time.sleep(1)
  print 'good bye'

def producer():
  queue = Queue.Queue()
  worker = Comsumer(queue)
  worker.start()# 开启消费者线程


  for i in range(5):
    queue.put('queue-{0}'.format(i))
  queue.put('quit')
  worker.join() #不是queue.join()

if __name__ == '__main__':
  producer()