Signals and Threads in Python 3.5 or so

Chris Angelico rosuav at gmail.com
Sun Oct 9 20:45:23 EDT 2016


On Mon, Oct 10, 2016 at 10:52 AM, Dan Stromberg <drsalists at gmail.com> wrote:
> That bug is: if you control-C the top-level process, all the
> subprocesses are left running.
>
> I've been thinking about making it catch SIGINT, SIGTERM and SIGHUP,
> and having it SIGKILL its active subprocesses upon receiving one of
> these signals.
>
> However, it's multithreaded, and I've heard that in CPython, threads
> and signals don't mix well.

Generally, expect SIGINT  to be handled by the main thread, and code
accordingly. But I've never used the low-level thread and _thread
modules, so I'd be inclined to follow through with the TODO and make
it use threading instead.

This simple example appears to work fine on my system (Debian Stretch,
Linux 4.6, amd64), but I can't make any hard-and-fast guarantees.

import threading
import signal
import random
import time

halt = False

def thread():
    global halt
    try:
        print(threading.current_thread(), "-- start")
        for i in range(random.randrange(10, 20)):
            time.sleep(1)
            if halt: break
            print(threading.current_thread(), "--", i)
    except KeyboardInterrupt:
        print(threading.current_thread(), "-- SIGINT")
        halt = True
    print(threading.current_thread(), "-- end")

for i in range(5):
    threading.Thread(target=thread).start()
thread()


Hit Ctrl-C and all threads will quickly terminate.

ChrisA



More information about the Python-list mailing list