简体   繁体   English

如何控制有条件的并行进程

[英]How to control parallel processes with condition

I want to control my processes while I not found working url.我想控制我的进程,而我没有找到工作 url。

But I have NameError: name 'status' is not defined due to threads not waiting to declare a variable但是我有NameError: name 'status' is not defined由于线程没有等待声明一个变量

import requests
from multiprocessing import Process


def first_function(i):
    global status
    status = False
    try:
        response = requests.get(f'https://ru.hexlet.io/{i}')
        if response.status_code == 200:
            status = True
    except Exception as e:
        print(str(e))


def second_function():
    for i in [1,2,3,4,5,6,'courses',8,9,10]:
        Process(target=first_function, args=(i, )).start()
        print(i)
        if status:
            print('working', i)
            break


if __name__ == '__main__':
    second_function()

I suggest using a multiprocessing.pool.Pool to limit the number of processes that are run concurrently (since you have indicated there might be a very large number of them).我建议使用multiprocessing.pool.Pool来限制同时运行的进程数(因为您已经指出它们可能非常多)。

If you use its apply_async() method to "submit" tasks to it, you can use the optional callback argumet to specify a function that will get called whenever one of the subprocesses finishes.如果你使用它的apply_async()方法向它“提交”任务,你可以使用可选的callback参数来指定一个 function,只要其中一个子进程完成,就会调用它。 This provides a way to terminate further processing by other processes submitted to the pool .这提供了一种方法来终止提交到pool的其他进程的进一步处理。

import multiprocessing as mp
import requests


def worker(i):
    try:
        response = requests.get(f'https://ru.hexlet.io/{i}')
        if response.status_code == 200:
            return i
    except Exception as exc:
        print(f'{i!r} caused {exc}')
    return None


if __name__ == '__main__':

    def notify(i):
        """Called when a Pool worker process finishes execution."""
        if i is not None:
            print(f'{i!r} worked')
            pool.terminate()  # Stops worker processes immediately.

    pool = mp.Pool()

    for i in [1,2,3,4,5,6,'courses',8,9,10]:
        pool.apply_async(worker, (i,), callback=notify)

    pool.close()
    pool.join()
    print('fini')

Output: Output:

'courses' worked
fini

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM