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

#python3
#product new data into the queue
#comsume data from the queue
from queue import Queue
import time , threading
class product_data(threading.Thread):
    def __init__(self,name,queue):
        threading.Thread.__init__(self,name=name)
        self.data = queue
    def run(self):
        print('start product___')
        for i in range(5):
            print('create new data: {0}'.format(i))
            self.data.put('put new data:{0} '.format(i,self.name))
            time.sleep(2)
        print('put data finished')
        return self.data
class comsume_data(threading.Thread):
    def __init__(self,name,queue):
        threading.Thread.__init__(self,name=name)
        self.data = queue
    def run(self):
        print('start get data')
        for i in range(5):
            small_data = self.data.get()
            print('get data:{0} from {1}'.format(small_data,self.name))
            time.sleep(5)
        print('get data finished')

def main():
    queue = Queue()
    new_product = product_data('pro_fuck',queue)
    new_comsume = comsume_data('com_fuck',queue)

    new_product.start()
    new_comsume.start()

    new_product.join()
    new_comsume.join()

if __name__ == '__main__':
    main()
参考:http://python.jobbole.com/87592/

简单案例:

#!/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()

好的例子:

https://cloud.tencent.com/developer/article/1047257

原文地址:https://www.cnblogs.com/hixiaowei/p/9096444.html