sawyl: (Default)
[personal profile] sawyl
According to the documentation, any signal sent to a multi-threaded python script will be delivered to the main thread. Thus, the easiest way to cleanly shut down a set of worker threads would seem to involve having each worker periodically check for a global variable which can be set to False by a signal handler routine registered by the main thread. For example:

import threading
import signal
import time

keep_going = True

def handler(s, f):
global keep_going
keep_going = False

def worker():
global keep_going
while keep_going:
print "Working..."
time.sleep(1)
print "Done"

def main():
signal.signal(signal.SIGINT, handler)
for i in range(1):
t = threading.Thread(target=worker)
t.start()
for t in threading.enumerate():
if t != threading.currentThread():
t.join()

main()

However, this does not work as expected. Why? Because, when the main thread issues the join() call, it sets a lock which prevents the signal handler code from interrupting — something that can be demonstrated by placing a sleep between the two loops. The solution? Replace the blocking join loop with one that times out, for example:

while True:
threads = threading.enumerate()
if len(threads) == 1: break
for t in threads:
if t != threading.currentThread():
t.join(1)

Which works for me...

Profile

sawyl: (Default)
sawyl

August 2018

S M T W T F S
   123 4
5 6 7 8910 11
12131415161718
192021222324 25
262728293031 

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Feb. 5th, 2026 05:29 am
Powered by Dreamwidth Studios