title: Interruptible thread join in Python
body: <p><strong>Is there any way to wait for termination of a thread, but still intercept signals?</strong> </p>
  
  <p>Consider the following <strong>C</strong> program:</p>
  
  <pre><code>#include &lt;signal.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;pthread.h&gt;
  #include &lt;stdlib.h&gt;
  
  void* server_thread(void* dummy) {
      sleep(10);
      printf("Served\n");
      return NULL;
  }
  
  void* kill_thread(void* dummy) {
      sleep(1); // Let the main thread join
      printf("Killing\n");
      kill(getpid(), SIGUSR1);
      return NULL;
  }
  
  void handler(int signum) {
      printf("Handling %d\n", signum);
      exit(42);
  }
  
  int main() {
      pthread_t servth;
      pthread_t killth;
  
      signal(SIGUSR1, handler);
  
      pthread_create(&amp;servth, NULL, server_thread, NULL);
      pthread_create(&amp;killth, NULL, kill_thread, NULL);
  
      pthread_join(servth, NULL);
  
      printf("Main thread finished\n");
      return 0;
  }
  </code></pre>
  
  <p>It ends after one second and prints:</p>
  
  <pre><code>Killing
  Handling 10
  </code></pre>
  
  <p>In contrast, here's my attempt to write it in <strong>Python</strong>:</p>
  
  <pre><code>#!/usr/bin/env python
  import signal, time, threading, os, sys
  
  def handler(signum, frame):
      print("Handling " + str(signum) + ", frame:" + str(frame))
      exit(42)
  signal.signal(signal.SIGUSR1, handler)
  
  def server_thread():
      time.sleep(10)
      print("Served")
  servth = threading.Thread(target=server_thread)
  servth.start()
  
  def kill_thread():
      time.sleep(1) # Let the main thread join
      print("Killing")
      os.kill(os.getpid(), signal.SIGUSR1)
  killth = threading.Thread(target=kill_thread)
  killth.start()
  
  servth.join()
  
  print("Main thread finished")
  </code></pre>
  
  <p>It prints:</p>
  
  <pre><code>Killing
  Served
  Handling 10, frame:&lt;frame object at 0x12649c0&gt;
  </code></pre>
  
  <p><strong>How do I make it behave like the C version?</strong></p>