Joining threads but allowing signals to main thread?

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top