Shutting worker threads down gracefully after signal, portably

Discussion in 'Python' started by Duncan Findlay, Jan 10, 2012.

  1. Suppose I've got a Python daemon that spawns a bunch of worker threads, waits for a singal (e.g. SIGTERM) and then shuts down the worker threads gracefully. What's the simplest way to do the signal handling portably across as many operating systems as possible (at least Linux and FreeBSD). Specifically, I'm interested in solutions where the main thread consumes no CPU, so no time.sleep(n) loops.

    The most obvious solution (below) does not work with on FreeBSD, because the signal gets delivered to a different thread and signal.pause() doesn't return.

    _shutdown = False

    def sig_handler(signum, frame):
    print 'handled'
    global _shutdown
    _shutdown = True

    if __name__ == '__main__':

    # Set up signal handling.
    signal.signal(signal.SIGTERM, sig_handler)

    # Start worker threads.
    workers = [Worker() for i in xrange(NUM_THREADS)]
    for worker in workers:
    worker.start()

    # Sleep until woken by a signal.
    while not _shutdown:
    signal.pause()

    # Shutdown work threads gracefully.
    for worker in workers:
    worker.shutdown()

    Any ideas? I've attached a more complete code sample.

    Thanks
    Duncan Findlay
     
    Duncan Findlay, Jan 10, 2012
    #1
    1. Advertisements

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?Qm9zc29tYQ==?=

    Windows 98 SE freezes when shutting down.

    =?Utf-8?B?Qm9zc29tYQ==?=, Jun 26, 2005, in forum: ASP .Net
    Replies:
    1
    Views:
    691
    Eddie
    Jun 27, 2005
  2. rooster575
    Replies:
    1
    Views:
    465
    Lau Lei Cheong
    Jul 2, 2004
  3. alex
    Replies:
    1
    Views:
    849
    Lau Lei Cheong
    Feb 4, 2005
  4. J-T
    Replies:
    4
    Views:
    9,704
  5. Darren Davison

    shutting down Resin

    Darren Davison, Dec 17, 2003, in forum: Java
    Replies:
    0
    Views:
    451
    Darren Davison
    Dec 17, 2003
  6. Murrgon
    Replies:
    5
    Views:
    1,100
  7. Jesper
    Replies:
    10
    Views:
    4,763
    D. Rush
    Sep 29, 2004
  8. Jack
    Replies:
    2
    Views:
    2,008
Loading...