我有一个系数为数字的函数.这取决于一些随机条件.

所以我要做的是在这个函数中运行多个处理器,首先找到因子的处理器返回值,所有处理器终止.

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

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()等.这些方法还将从辅助函数返回值.

例如(我用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

Python相关问答推荐

Python 3.12中的通用[T]类方法隐式类型检索

@Property方法上的inspect.getmembers出现意外行为,引发异常

在Python中处理大量CSV文件中的数据

将数据框架与导入的Excel文件一起使用

如何访问所有文件,例如环境变量

从spaCy的句子中提取日期

用砂箱开发Web统计分析

如何在达到end_time时自动将状态字段从1更改为0

Geopandas未返回正确的缓冲区(单位:米)

幂集,其中每个元素可以是正或负""""

LocaleError:模块keras._' tf_keras. keras没有属性__internal_'''

Python避免mypy在相互引用中从另一个类重定义类时失败

通过追加列表以极向聚合

如何在Gekko中使用分层条件约束

在极点中读取、扫描和接收有什么不同?

删除特定列后的所有列

当我定义一个继承的类时,我可以避免使用`metaclass=`吗?

为什么在Python中00是一个有效的整数?

如何在Python中实现高效地支持字典和堆操作的缓存?

对列中的数字进行迭代,得到n次重复开始的第一个行号