Search code examples
pythonmultiprocessingterminate

Python Multiprocessing example. never terminates


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()

Solution

  • 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.