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

How to do a race between multiprocessors in python

我有一个函数可以分解一个数字。这取决于一些随机条件。

所以我想做的是 运行 这个函数中的多个处理器和首先找到因子的处理器 returns 值和所有处理器终止。

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

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

您可以使用 multiprocessing.Pool 及其方法 map()imap_unordered() 等。这些 return 也将来自工作函数的值。

示例(我使用 time.sleep() 来模拟一些 time-intesive 计算):

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