zoukankan      html  css  js  c++  java
  • 生产者-消费者模型-线程安全队列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

  • 相关阅读:
    布隆过滤器原理与应用场景
    【转】程序员的世界真的很难懂~
    IDEA 2019.2.4 破解安装教程
    【转】只有程序员才能看得懂的段子
    Linux 正则表达式
    【转】雷军做程序员时写的博客,很强大!
    如何同步 Linux 集群系统时间
    百度共享云盘
    Shell 脚本 test 命令详解
    Linux 命令大全
  • 原文地址:https://www.cnblogs.com/hixiaowei/p/9096444.html
Copyright © 2011-2022 走看看