• 【Python】多进程-队列


    #练习:队列
    from multiprocessing import Process, Queue 
    
    def offer(queue): 
      # 入队列
      queue.put("Hello World") 
    
    if __name__ == '__main__': 
      # 创建一个队列实例
      q = Queue()
      p = Process(target = offer, args = (q,)) 
      p.start() 
      print q.get() # 出队列
      p.join()
    
    
    #练习
    import time
    from multiprocessing import Process, Queue 
    
    def set_data(queue): 
      # 入队列
      for i in range(10):
          time.sleep(2)
          queue.put("Hello World"+str(i)) 
    
    def get_data(queue): 
      for i in range(10):
      # 入队列
          time.sleep(1)
          print queue.get("Hello World") 
    
    
    if __name__ == '__main__': 
      # 创建一个队列实例
      q = Queue()
      p1 = Process(target = set_data, args = (q,)) 
      p2 = Process(target = get_data, args = (q,))
      p1.start() 
      p2.start()
     
      p1.join()
      p2.join()
      print u"队列是否为空?",q.empty()
    
    
    #练习:写两个队列,一个用来写,一个用来读,一边写,一边读
    from multiprocessing import Process, Queue
    
    def input_queue(queue_input):
        for i in range(11):
            if queue_input.full():
                print "队列已经满啦"
            else:
                queue_input.put(i)
                #print queue_input
    
    def get_queue(queue_get):
        for i in range(11):
            if queue_get.empty():
                print u"队列已经空啦"
            else:
                print queue_get.get()
    
    
    if __name__=="__main__":
        q=Queue()
        p1=Process(target=input_queue,args=(q,)) #写进程和读进程是同时执行的,只不过通过sleep时间来控制读和写的速度
        p2=Process(target=get_queue,args=(q,))
    
        p1.start()
        p2.start()
    
        p2.join()
        p2.join()
  • 相关阅读:
    HDU 2842 (递推+矩阵快速幂)
    HDU 2838 (DP+树状数组维护带权排序)
    HDU 2836 (离散化DP+区间优化)
    HDU 2831 (贪心)
    HDU 2818 (矢量并查集)
    HDU 2822 (BFS+优先队列)
    HDU 3090 (贪心)
    HDU 3089 (快速约瑟夫环)
    XCOJ 1103 (LCA+树链最大子段和)
    HDU 3078 (LCA+树链第K大)
  • 原文地址:https://www.cnblogs.com/jingsheng99/p/8713304.html
Copyright © 2020-2023  润新知