1

I'm writing some simple code and I use Pygame for graphics and I have a thread that draws everything. When I call sys.exit() or just ctrl+c, the main program exits but the thread seems to still be alive. I think I need to shut it down before. How do I do that?

Example:

import threading

class Bla(threading.Thread):
    def run(self):
        print "I draw here"

Bla().start()

while True:
     if user_wants_to_end:
         sys.exit()

And when I do want to exit the program doesn't exit! How do I shut the thread down?

yannbane
  • 11
  • 1
  • 2
  • 4
    "Simple code" and "thread" in the same sentence? Tsk, tsk. Don't use multithreading because it seems to be a good idea, use it when you actually need it. – Cat Plus Plus Jul 14 '11 at 14:36
  • 1
    This looks like a duplicate; you might want to look [here](http://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python/325528#325528) for some help. – Mahdi Yusuf Jul 14 '11 at 14:36
  • This program does not exactly show your problem, because it does exit quite quickly. The problem can be illustrated if you add something like `time.sleep(1000000)` in the `run()` method, though. – Eric O. Lebigot Jul 14 '11 at 16:54
  • Make `Bla.run()` check a global flag or something that signals it when it's time to quit. – martineau Jul 14 '11 at 19:02

1 Answers1

2

Python programs exit when all non-daemon threads are done.

class Bla(threading.Thread):
    daemon = True # Make the thread daemon
    def run(self):
        print "I draw here"
Miki Tebeka
  • 13,428
  • 4
  • 37
  • 49
  • For reference: "The entire Python program exits when no alive non-daemon threads are left." (threading module documentation). – Eric O. Lebigot Jul 14 '11 at 16:42
  • Isn't there a way to ask a thread to terminate, from the main program, without handling this specifically in the thread code? – Eric O. Lebigot Jul 14 '11 at 16:43
  • I pretty sure the answer is no. Either you use a process (see muliprocessing) or have explicit checks in your thread code (usually using Events). – Miki Tebeka Jul 14 '11 at 17:27