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

  • 相关阅读:
    POJ-2112 Optimal Milking(floyd+最大流+二分)
    网络流之最大流与最小费用流入门&&模板
    0316 校赛训练赛3 解题报告
    string的子串截取
    hash题目大汇总
    Codeforces Round #235 (Div. 2)
    poj2002 -- 点的hash
    hlgHCPC2014校赛训练赛 1 BB.序列问题
    树状数组模板,RMQ模板
    从未放弃--2014.1.21
  • 原文地址:https://www.cnblogs.com/hixiaowei/p/9096444.html
Copyright © 2011-2022 走看看