Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ignores SIGINT in multithreaded programs - how to fix that?

Tags:

python

I have Python 2.6 on MacOS X and a multithread operation. Following test code works fine and shuts down app on Ctrl-C:

import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
  sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
  def run( self ) :
    while True :
      time.sleep( 1 )
thread = WorkThread()
thread.start()
time.sleep( 1000 )

But if i change only one string, adding some real work to worker thread, the app will never terminate on Ctrl-C:

import threading, time, os, sys, signal
def SigIntHandler( signum, frame ) :
  sys.exit( 0 )
signal.signal( signal.SIGINT, SigIntHandler )
class WorkThread( threading.Thread ) :
  def run( self ) :
    while True :
      os.system( "svn up" ) # This is really slow and can fail.
      time.sleep( 1 )
thread = WorkThread()
thread.start()
time.sleep( 1000 )

Is it possible to fix it, or python is not intended to be used with threading?

like image 440
grigoryvp Avatar asked Mar 25 '26 19:03

grigoryvp


1 Answers

A couple of things which may be causing your problem:

  1. The Ctrl-C is perhaps being caught by svn, which is ignoring it.
  2. You are creating a thread which is a non-daemon thread, then just exiting the process. This will cause the process to wait until the thread exits - which it never will. You need to either make the thread a daemon or give it a way to terminate it and join() it before exiting. While it always seems to stop on my Linux system, MacOS X behaviour may be different.

Python works well enough with threads :-)

Update: You could try using subprocess, setting up the child process so that file handles are not inherited, and setting the child's stdin to subprocess.PIPE.

like image 140
Vinay Sajip Avatar answered Mar 27 '26 08:03

Vinay Sajip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!