Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this python program sometimes fail to exit?

I wrote a test program, which has two processes. The father process gets data from a Queue, and the child puts data into it. There is a signal handler which tells the program to exit. However, it does not exit sometimes when I send the signal SIGTERM to the pid(child process) I printed, and it seems to be having a deadlock.

import os
import sys 
import multiprocessing
import time
import signal

bStop = False
def worker(que):
    signal.signal(signal.SIGTERM,sighandler)
    print 'worker:',os.getpid()
    for i in range(100000000):
        que.put(i)

    print 'STOP'

def sighandler(num,frame):
    print 'catch signal'
    q.put('STOP')
    sys.exit(0)
q = multiprocessing.Queue(100)
p = multiprocessing.Process(target=worker,args=(q,))
p.start()

for item in iter(q.get,'STOP'):
    print 'get',item
    pass
print 'main stop'
p.join()
like image 596
renenglish Avatar asked Jun 20 '11 11:06

renenglish


People also ask

How do you exit a Python program?

The exit() function is a Python command to exit program and an alias of the quit() function. It makes Python more user-friendly as some may intuitively expect exit() to be the exit command and some may use quit(). Both exit() and quit() are used to exit the program.

Why quit function is not working in Python?

You are missing the pair of brackets that come after the quit command. The quit command is calling a function just like choose_level does, so you need to tell Python what parameters you want to pass in. Every function call needs a pair of brackets telling Python what arguments you want.

How do you exit code block in Python?

To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program from running. It is the most reliable, cross-platform way of stopping code execution.

How do you exit a function execution in Python?

Technique 1: Using quit() function The in-built quit() function offered by the Python functions, can be used to exit a Python program. As soon as the system encounters the quit() function, it terminates the execution of the program completely.


1 Answers

Unless you are running python 3 you should be using xrange instead of range for a loop that large. Python tends to choke once it exceeds a certain list size and so you really really need to move to generators by that point.

That very well could be the issue your seeing right now.

like image 164
John Avatar answered Oct 05 '22 12:10

John