[英]Python multiprocessing example never terminates when the dataset is too large
[英]Python Multiprocessing example. never terminates
我是Python多重處理的新手,遇到了一個教程,因此嘗試檢查其多重處理。 在這里,進程不會終止。 他們永遠在奔跑。 怎么了。? 我讀到,當可選參數為true時,該過程不會終止。 因此,我在那兒放了空聲明。 但該過程仍不會終止。 請指教。 謝謝。 我正在使用的機器具有Python 2.7.6,這是我的代碼
from multiprocessing import Process
from Queue import Empty,Queue
import math
def isprime(n):
if not isinstance(n,int):
raise TypeError("argument is not of int type")
if n<2:
return False
if n==2:
return True
max= int(math.ceil(math.sqrt(n)))
i=2
while i<=max:
if n%i==0:
return False
return True
def sum_primes(n):
return sum([x for x in xrange(2,n) if isprime(x)])
def do_work(q):
while True:
try:
x=q.get(block=False)
print sum_primes(x)
except Empty:
break
if __name__=="__main__":
work_queue=Queue()
for i in range (100000,5000000,100000):
work_queue.put(i)
processes=[Process(target=do_work, args=(work_queue,)) for i in range(8)]
for p in processes:
p.start()
for p in processes:
p.join()
您的第一個while循環:
while i<=max:
if n%i==0:
return False
永遠不會終止。 您沒有在增加i
或在減少max
所以如果條件評估為true,它將始終為true。 為什么即使在while循環中它也應該只是if語句。
如上所述,您的問題是第一個while循環。 這是代碼的簡化版本,可修復while循環問題,似乎可以完成您想要的事情以及多進程(使用池而不是隊列):
import multiprocessing as mp
import math
def isprime(n):
if not isinstance(n,int):
raise TypeError("argument is not of int type")
if n<2:
return False
if n==2:
return True
max= int(math.ceil(math.sqrt(n)))
i=2
while i<=max:
if n%i==0:
return False
else:
i += 1
return True
def sum_primes(n):
return = sum([x for x in xrange(2,n) if isprime(x)])
if __name__=="__main__":
jobs = range(100000,500000,100000)
pool = mp.Pool()
post = pool.map(sum_primes, jobs)
pool.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.