Reputation: 75
I'm fairly new to Python Multiprocessing and i came across a tutorial and hence tried to check its multiprocessing. Here the processes are not getting terminated. they are running forever. what's wrong.? I read that when optional arguments are true the process doesn't terminate. hence I've put empty statement over there. but still the process doesn't terminate. Please advise. Thanks. The machine i'm using has Python 2.7.6 Here's my code
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()
Upvotes: 1
Views: 1091
Reputation: 2449
As mentioned above, your problem is the first while loop. Here's a simplified version of your code that fixes the while loop issue, seems to do what you want it to, and also multiprocesses (with pool instead of queue):
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()
Upvotes: 2
Reputation: 1224
Your first while loop:
while i<=max:
if n%i==0:
return False
will never terminate. You are not increasing i
nor decreasing max
so if the condition evaluates true it will always be true. Why is this even in a while loop it should just be the if statement.
Upvotes: 6