【问题标题】:How to use python multiprocessing pool in continuous loop如何在连续循环中使用python多处理池
【发布时间】:2017-06-09 04:35:09
【问题描述】:

我正在使用 python 多处理库来执行 selenium 脚本。我的代码如下:

#-- start and join multiple threads ---
thread_list = []
total_threads=10 #-- no of parallel threads
for i in range(total_threads):
    t = Process(target=get_browser_and_start, args=[url,nlp,pixel])
    thread_list.append(t)
    print "starting thread..."
    t.start()

for t in thread_list:
    print "joining existing thread..."
    t.join()

据我了解join() 函数,它将等待每个进程完成。但是我希望一旦一个进程被释放,它就会被分配另一个任务来执行新的功能。

可以这样理解:

假设首先启动了 8 个进程。

no_of_tasks_to_perform = 100

for i in range(no_of_tasks_to_perform):
    processes start(8)
    if process no 2 finished executing, start new process
    maintain 8 process at any point of time till 
    "i" is <= no_of_tasks_to_perform

【问题讨论】:

    标签: python selenium-webdriver python-multiprocessing


    【解决方案1】:

    不要时不时启动新进程,而是尝试将所有任务放入multiprocessing.Queue(),并启动8个长时间运行的进程,在每个进程中不断访问任务队列以获得新的任务,然后做这项工作,直到没有任务了。

    在你的情况下,它更像是这样的:

    from multiprocessing import Queue, Process
    
    def worker(queue):
        while not queue.empty():
            task = queue.get()
    
            # now start to work on your task
            get_browser_and_start(url,nlp,pixel) # url, nlp, pixel can be unpacked from task
    
    def main():
        queue = Queue()
    
        # Now put tasks into queue
        no_of_tasks_to_perform = 100
    
        for i in range(no_of_tasks_to_perform):
            queue.put([url, nlp, pixel, ...]) 
    
        # Now start all processes
        process = Process(target=worker, args=(queue, ))
        process.start()
        ...
        process.join()
    

    【讨论】:

    • @shane ,这个设置中的 8 个处理器在哪里?应该是简单的:process.start(8)。我有一个自定义的 python 模块,我可以初始化该类以建立 webDriver 实例,然后使用队列中的参数调用我的抓取函数。但是我不需要将 8 个不同的 webDrivers 实例化到一个池中吗?因为我想知道一个 X-window 帧缓冲区(Xvfb)和无头 chromedriver 实例如何充当 8 个不同的进程来执行任务队列(数千个) ?
    • 在此设置中,您实际上手动启动 8 个进程(或任何您想要的),并使每个进程成为一个长时间运行的进程以不断获取新任务,(在您的情况下,实例化浏览器并执行操作),例如process1 = Process(target=worker, args=(queue, )) ... process8 ...。如果您想使用multiprocessing.Pool,这是一个不同的设置,您需要使用map 传递您的函数,但在您的情况下它实际上并不方便,尤其是在涉及多个参数时,请查看:stackoverflow.com/a/5442981/7405394
    • @shane , 'hmm... 我错过了你开场白中的粗体字;对不起/谢谢。另一种选择可能是instantiate the webDriver inside the worker of the queue,然后通过定时执行提示来粗略控制启动的进程数量——允许进程在新进程出现时终止。这实际上帮助我更好地控制通过代理切换器每小时发出的请求数量,而处理器数量可能因 I/O 和等待而变化。 (???)
    猜你喜欢
    • 2014-04-30
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2011-08-23
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多