Filling a queue and managing multiprocessing in python

前端 未结 2 1898
暗喜
暗喜 2020-11-28 10:15

I\'m having this problem in python:

  • I have a queue of URLs that I need to check from time to time
  • if the queue is filled up, I need to process each it
2条回答
  •  孤街浪徒
    2020-11-28 10:29

    You could use the blocking capabilities of queue to spawn multiple process at startup (using multiprocessing.Pool) and letting them sleep until some data are available on the queue to process. If your not familiar with that, you could try to "play" with that simple program:

    import multiprocessing
    import os
    import time
    
    the_queue = multiprocessing.Queue()
    
    
    def worker_main(queue):
        print os.getpid(),"working"
        while True:
            item = queue.get(True)
            print os.getpid(), "got", item
            time.sleep(1) # simulate a "long" operation
    
    the_pool = multiprocessing.Pool(3, worker_main,(the_queue,))
    #                            don't forget the coma here  ^
    
    for i in range(5):
        the_queue.put("hello")
        the_queue.put("world")
    
    
    time.sleep(10)
    

    Tested with Python 2.7.3 on Linux

    This will spawn 3 processes (in addition of the parent process). Each child executes the worker_main function. It is a simple loop getting a new item from the queue on each iteration. Workers will block if nothing is ready to process.

    At startup all 3 process will sleep until the queue is fed with some data. When a data is available one of the waiting workers get that item and starts to process it. After that, it tries to get an other item from the queue, waiting again if nothing is available...

提交回复
热议问题