Multiprocessing Queue in Python

后端 未结 5 902
抹茶落季
抹茶落季 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:06

    The code below may not be very relevant but I post it for your comments/feedbacks so we can learn together. Thank you!

    import multiprocessing
    
    def boss(q,nameStr):
      source = range(1024)
      for item in source:
        q.put(nameStr+' '+str(item))
      q.put(None) # send termination sentinel, one for each process
    
    def worker(q,nameStr):
      while True:
         item = q.get()
         if item is None: # detect sentinel
           break
         print '%s processed %s' % (nameStr,item) # do something useful
    
    q = multiprocessing.Queue()
    
    procs = []
    
    num_procs = 4
    for i in range(num_procs):
      nameStr = 'ID_'+str(i)
      p = multiprocessing.Process(target=worker, args=(q,nameStr))
      procs.append(p)
      p = multiprocessing.Process(target=boss,   args=(q,nameStr))
      procs.append(p)
    
    for j in procs:
      j.start()
    for j in procs:
      j.join()
    

提交回复
热议问题