[英]multiprocessing find prime numbers in an intervalle
in python 3 i have to find prime numbers in an interval [a,b] using multiprocessing pipes in specific , here is my code :在python 3中,我必须使用特定的多处理管道在区间[a,b]中找到素数,这是我的代码:
import sys
import multiprocessing
import os
import time
def isprime(conn):
while 1:
num = conn.recv()
print(num)
if num < 2:
return None
for i in range(2, num):
if (num % i) == 0:
return None
else:
print(num)
def psend(conn,num):
for i in num:
conn.send(i)
if __name__ == "__main__":
pid = os.fork()
p_conn, c_conn = multiprocessing.Pipe()
start_time = time.perf_counter()
p1 = multiprocessing.Process(target=psend, args=(p_conn,range(0,31)))
p2 = multiprocessing.Process(target=isprime, args=(c_conn,))
p1.start()
p2.start()
finish_time = time.perf_counter()
print(f"Program finished in {finish_time-start_time} seconds")
i expected to get all prime numbers but the child get only the first number which is :0 then it closed我希望得到所有素数,但孩子只得到第一个数字,即:0 然后它关闭
When a Process target returns, it ends.当 Process 目标返回时,它结束。 Therefore, for this scenario, it has to run in a loop and somehow know when to stop processing.因此,对于这种情况,它必须循环运行并以某种方式知道何时停止处理。
In this example, we send values from a range then, once the range is exhausted, we send -1 as an indication that a no more data will be sent.在此示例中,我们从一个范围发送值,然后,一旦范围用完,我们发送 -1 作为不再发送数据的指示。
from multiprocessing import Pipe, Process
from sympy import isprime as ISPRIME
from time import perf_counter
def isprime(p):
while (n := p.recv()) >= 0:
if ISPRIME(n):
print(n)
def psend(p, num):
for i in num:
p.send(i)
p.send(-1) # inform isprime() function that no more data will be sent
def main():
start = perf_counter()
p, c = Pipe(False)
(p1 := Process(target=psend, args=(c, range(0, 31)))).start()
(p2 := Process(target=isprime, args=(p,))).start()
end = perf_counter()
for p in p1, p2:
p.join()
print(f'Duration = {end-start:.4f}s')
if __name__ == '__main__':
main()
Output:输出:
2
3
5
7
11
13
17
19
23
29
Duration = 0.0095s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.