作家
登录

用Python多线程实现生产者消费者模式

作者: 来源: 2017-05-16 15:29:04 阅读 我要评论

  •         self.data=http://developer.51cto.com/art/201705/queue
  •  
  •     def run(self): 
  •  
  •         for i in range(5): 
  •  
  •             val = self.data.get() 
  •  
  •             print("%s is consuming. %d in the queue is consumed!" % (self.getName(),val)) 
  •  
  •             time.sleep(random.randrange(10)) 
  •  
  •         print("%s finished!" % self.getName()) 
  •  
  •   
  •  
  • def main(): 
  •  
  •     queue = Queue() 
  •  
  •     producer = Producer('Producer',queue) 
  •  
  •     consumer = Consumer('Consumer',queue) 
  •  
  •   
  •  
  •     producer.start() 
  •  
  •     consumer.start() 
  •  
  •   
  •  
  •     producer.join() 
  •  
  •     consumer.join() 
  •  
  •     print 'All threads finished!' 
  •  
  •   
  •  
  • if __name__ == '__main__'
  •  
  •     main()  
  • 履行结不雅可能如下:

    1. Producer is producing 0 to the queue! 
    2.  
    3. Consumer is consuming. 0 in the queue is consumed! 
    4.  
    5. Producer is producing 1 to the queue! 
    6.  
    7. Producer is producing 2 to the queue! 
    8.  
    9. Consumer is consuming. 1 in the queue is consumed! 
    10.  
    11. Consumer is consuming. 2 in the queue is consumed! 
    12.  
    13. Producer is producing 3 

        推荐阅读

        如何使用VCHA创建集群保护负载

      VCHA(VCenter Server High Availability)应用一个包含三个节点——active、passive和witness——的集群来尽量避免体系故障可能带来的影响。如不雅治理员想要应用 vC>>>详细阅读


      本文标题:用Python多线程实现生产者消费者模式

      地址:http://www.17bianji.com/lsqh/35243.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)