开发者

Why does this python program sometimes fail to exit?

开发者 https://www.devze.com 2023-03-13 22:25 出处:网络
I wrote a test program, wh开发者_如何学运维ich 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.

I wrote a test program, wh开发者_如何学运维ich 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()


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消