python - 如何在 python 中的多处理器之间进行竞赛

我有一个计算数字的函数。这取决于一些随机条件。

所以我想做的是在这个函数中运行多个处理器,找到这个因素的处理器首先返回 value 并且所有处理器都终止。

到目前为止我所拥有的是非常错误的。处理器没有终止,我也不知道如何获取函数返回的 value

flag = False
def rho(n, processor):

    while True:
        x = random.randrange(1, n-1)
        x2 = x
        gcd = 1
        c = random.randrange(1, n-1)

        while gcd == 1:
            x = (x**2 + c) % n
            x2 = (x2**2 + c) % n
            x2 = (x2**2 + c) % n
            gcd = math.gcd(abs(x - x2), n)

        if gcd != n:
            flag = True
            print("Factor was found from "+process+" and is ", gcd)
            return gcd


if __name__ == "__main__":
    p1 = multiprocessing.Process(target=rho, args=(91, "process 1" ))
    p2 = multiprocessing.Process(target=rho, args=(91, "process 2"))
    p1.start()
    p2.start()

    if flag:
        p1.terminate()
        p2.terminate()

输出是:

Factor was found from process 2 and is  13
Factor was found from process 1 and is  7

回答1

您可以使用 https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool 及其方法 map()imap_unordered() 等。这些方法也会从工作函数返回 values。

示例(我使用 time.sleep() 来模拟一些时间密集型计算):

from time import sleep
from multiprocessing import Pool


def rho(params):
    n, processor = params
    # your computation here
    # ...
    sleep(n)
    print("Factor was found from " + processor + " and is 42")
    return 42


if __name__ == "__main__":
    with Pool() as pool:
        for result in pool.imap_unordered(
            rho, ((10, "process 1"), (1, "process 2"))
        ):
            print("Result I got:", result)
            break  # <-- I don't want other results, so break

印刷:

Factor was found from process 2 and is 42
Result I got: 42

编辑:两个不同的功能:

from time import sleep
from multiprocessing import Pool


def fn1(n, p):
    sleep(n)
    print("Factor was found from " + p + " and is 42")
    return 42


def fn2(n, p):
    sleep(n)
    print("Factor was found from " + p + " and is 99")
    return 99


def rho(params):
    what_to_call, n, processor = params
    return what_to_call(n, processor)


if __name__ == "__main__":
    with Pool() as pool:
        for result in pool.imap_unordered(
            rho, ((fn1, 10, "process 1"), (fn2, 1, "process 2"))
        ):
            print("Result I got:", result)
            break  # <-- I don't want other results, so break

相似文章

随机推荐

最新文章