safest way to kill a thread

M

martinnitram

Dear all,
in python, a thread can be created by t = threading.Thread. But i
found that when the main (and the thread) program is running and user
use Crtl+C/Crtl+Z to break the program abnormally, the thread is still
running and needed to kill manually (by the pid). Is there had any
safest way to kill/exit the thread program under python (when the
thread program part is a forever loop)?

Thank a lot
 
L

limodou

Using Thread's method setDaemon() before you call the start() method.
Just like :

t.setDaemon(True)
t.start()
 
M

martinnitram

limodou said:
Using Thread's method setDaemon() before you call the start() method.
Just like :
t.setDaemon(True)
t.start()
thank for fast reply.
from python.org doc, said that setDaemon() function as
"The entire Python program exits when no active non-daemon threads
are left."
is it mean that when the main program exit (normally/abnormally), all
threads created will also exit?
Thank again.
 
L

limodou

I think only those threads which invoked with setDaemon() method will
exit, and others will not, as the main program exit.
 
M

martinnitram

Great thank for your helping.
Should the 'daemonic' flag at setDaemon() function set to 1/TRUE or
0/FALSE to do such action?
 
H

hoxide

To Catch the "SystemExit"

import thread
from time import sleep
import sys

def t1():
try:
i=0
while 1:
print i+1
i += 1
sleep(1)
except SystemExit:
pass

thread.start_new_thread(t1, ())
sleep(3)


This Question was also asked in Python-chinese .
 
P

Peter Hansen

Should the 'daemonic' flag at setDaemon() function set to 1/TRUE or
0/FALSE to do such action?

First of all, it's "True" and "False" in Python, not TRUE
and FALSE.

Secondly, the answer to the question was in the previous
message where "limodou" told you about this in the first
place. Go back and read it again...

-Peter
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,141
Latest member
BlissKeto
Top