I have a function that factor a number. It depends on some random condition.
So what I am trying to do it’s to run multiple processors in this function and the processor that finds the factor first returns the value and all processors terminate.
What I have so far is very wrong. The processors are not terminating and I also don’t know how to get the value that was returned by the function
JavaScript
x
32
32
1
flag = False
2
def rho(n, processor):
3
4
while True:
5
x = random.randrange(1, n-1)
6
x2 = x
7
gcd = 1
8
c = random.randrange(1, n-1)
9
10
while gcd == 1:
11
x = (x**2 + c) % n
12
x2 = (x2**2 + c) % n
13
x2 = (x2**2 + c) % n
14
gcd = math.gcd(abs(x - x2), n)
15
16
if gcd != n:
17
flag = True
18
print("Factor was found from "+process+" and is ", gcd)
19
return gcd
20
21
22
if __name__ == "__main__":
23
p1 = multiprocessing.Process(target=rho, args=(91, "process 1" ))
24
p2 = multiprocessing.Process(target=rho, args=(91, "process 2"))
25
p1.start()
26
p2.start()
27
28
if flag:
29
p1.terminate()
30
p2.terminate()
31
32
The output is:
JavaScript
1
4
1
Factor was found from process 2 and is 13
2
Factor was found from process 1 and is 7
3
4
Advertisement
Answer
You can use multiprocessing.Pool
and it’s methods map()
, imap_unordered()
etc. These will return also values from worker functions.
Example (I used time.sleep()
to simulate some time-intesive computation):
JavaScript
1
21
21
1
from time import sleep
2
from multiprocessing import Pool
3
4
5
def rho(params):
6
n, processor = params
7
# your computation here
8
# ...
9
sleep(n)
10
print("Factor was found from " + processor + " and is 42")
11
return 42
12
13
14
if __name__ == "__main__":
15
with Pool() as pool:
16
for result in pool.imap_unordered(
17
rho, ((10, "process 1"), (1, "process 2"))
18
):
19
print("Result I got:", result)
20
break # <-- I don't want other results, so break
21
Prints:
JavaScript
1
3
1
Factor was found from process 2 and is 42
2
Result I got: 42
3
EDIT: Two different functions:
JavaScript
1
29
29
1
from time import sleep
2
from multiprocessing import Pool
3
4
5
def fn1(n, p):
6
sleep(n)
7
print("Factor was found from " + p + " and is 42")
8
return 42
9
10
11
def fn2(n, p):
12
sleep(n)
13
print("Factor was found from " + p + " and is 99")
14
return 99
15
16
17
def rho(params):
18
what_to_call, n, processor = params
19
return what_to_call(n, processor)
20
21
22
if __name__ == "__main__":
23
with Pool() as pool:
24
for result in pool.imap_unordered(
25
rho, ((fn1, 10, "process 1"), (fn2, 1, "process 2"))
26
):
27
print("Result I got:", result)
28
break # <-- I don't want other results, so break
29