Multiprocessing Queue in Python

后端 未结 5 896
抹茶落季
抹茶落季 2020-12-07 23:48

I\'m trying to use a queue with the multiprocessing library in Python. After executing the code below (the print statements work), but the processes do not quit after I call

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-08 00:09

    try this:

    import multiprocessing
    
    num_procs = 4
    def do_work(message):
      print "work",message ,"completed"
    
    def worker():
      for item in iter( q.get, None ):
        do_work(item)
        q.task_done()
      q.task_done()
    
    q = multiprocessing.JoinableQueue()
    procs = []
    for i in range(num_procs):
      procs.append( multiprocessing.Process(target=worker) )
      procs[-1].daemon = True
      procs[-1].start()
    
    source = ['hi','there','how','are','you','doing']
    for item in source:
      q.put(item)
    
    q.join()
    
    for p in procs:
      q.put( None )
    
    q.join()
    
    for p in procs:
      p.join()
    
    print "Finished everything...."
    print "num active children:", multiprocessing.active_children()
    

提交回复
热议问题