我有一个可以分解数字的函数。这取决于一些随机条件。
所以我想做的是在这个函数中运行多个处理器,首先找到该因子的处理器返回该值,然后所有处理器终止。
到目前为止我所得到的都是非常错误的。处理器没有终止,我也不知道如何获取函数返回的值
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 中进行多处理器之间的竞争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72243182/