L
Lloyd Zusman
I have a python-2.5 program running under linux in which I spawn a
number of threads. The main thread does nothing while these subsidiary
threads are running, and after they all complete, the main thread will
then exit.
I know that I can manage this through the use of Thread.join(), but
when I do it as follows, the main thread doesn't respond to signals:
import sys, time, signal, threading
signaled = False
class Signaled(Exception):
pass
def sighandler(signum, frame):
global signaled
print 'aborted!'
signaled = True
def sigtest():
global signaled
if signaled:
raise Signaled
def myfunc(arg):
while True:
try:
sigtest()
# do something
except Signaled:
return
threads = []
for a in sys.argv[1:]:
t = threading.Thread(myfunc, args=(a,))
threads.append(t)
# do some initialization
for s in (signal.SIGHUP, \
signal.SIGINT, \
signal.SIGQUIT, \
signal.SIGTERM):
signal.signal(s, sighandler)
for t in threads:
t.start()
for t in threads:
t.join()
sys.exit(0)
However, if I get rid of the t.join() loop and replace the last three
executable lines of the program with these, the main thread responds to
signals just fine:
...
while threading.activeCount() > 1:
time.sleep(0.001)
sys.exit(0)
Is there any way to allow my program to respond to signals without
having to busy-wait in the main thread?
Thanks in advance.
number of threads. The main thread does nothing while these subsidiary
threads are running, and after they all complete, the main thread will
then exit.
I know that I can manage this through the use of Thread.join(), but
when I do it as follows, the main thread doesn't respond to signals:
import sys, time, signal, threading
signaled = False
class Signaled(Exception):
pass
def sighandler(signum, frame):
global signaled
print 'aborted!'
signaled = True
def sigtest():
global signaled
if signaled:
raise Signaled
def myfunc(arg):
while True:
try:
sigtest()
# do something
except Signaled:
return
threads = []
for a in sys.argv[1:]:
t = threading.Thread(myfunc, args=(a,))
threads.append(t)
# do some initialization
for s in (signal.SIGHUP, \
signal.SIGINT, \
signal.SIGQUIT, \
signal.SIGTERM):
signal.signal(s, sighandler)
for t in threads:
t.start()
for t in threads:
t.join()
sys.exit(0)
However, if I get rid of the t.join() loop and replace the last three
executable lines of the program with these, the main thread responds to
signals just fine:
...
while threading.activeCount() > 1:
time.sleep(0.001)
sys.exit(0)
Is there any way to allow my program to respond to signals without
having to busy-wait in the main thread?
Thanks in advance.