473,756 Members | 3,973 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

thread, threading; how to kill a thread?

Greetings Pythonists;

I have limited experience with threaded apps and plenty with old style
forked heavyweight multi-processing apps.

Using Python 2.3.3 on a Redhat 7.x machine.

Wondering if there is a simple way from a main python program to kill
a running thread? I see with the 'threading' module the way daemonic
threads behave when the main program finishes.

But suppose we have a simple thread running a function like;

def timedLoop():
while True:
time.sleep(10)
doSomething()

All I am trying to do is stop that thread immediatly from the main
program and it is unclear how to do this. I see that using
del(threadObj) on the thread object that's running the loop function
does nothing.

Didn't notice anything obvious in the docs like a 'kill' method or
similar. I don't necessarily want the main program to exit, just to
kill one or more threads.

Locks, conditions, semafores, signals?

ARG! For heavens sake, what am I missing?

Thanks
--
-------------------------------------------------------------------------------
Jerry Sievers 305 854-3001 (home) WWW ECommerce Consultant
305 321-1144 (mobile http://www.JerrySievers.com/
Jul 18 '05 #1
12 18894
Jerry Sievers wrote:
I have limited experience with threaded apps and plenty with old style
forked heavyweight multi-processing apps.

Wondering if there is a simple way from a main python program to kill
a running thread?

There is no way to 'kill' a thread in Python. You will need to do
something like

def timedLoop():
while not done:
time.sleep(10)
doSomething()

Clearly, done should be implemented as an instance variable of the
thread object rather than a global, and it should probably be set by a
setDone() method that does any necessary locking. And yes, the thread
will not terminate immediately, but only the next time the loop test is
executed.

Aaron

Jul 18 '05 #2
Jerry Sievers wrote:
Wondering if there is a simple way from a main python program to kill
a running thread?
No.
I see with the 'threading' module the way daemonic
threads behave when the main program finishes.
This is one of several approaches, any of which -- or none of
which -- might be suitable for you.

What drives your need for this behaviour? The answer
will determine the best approach.
All I am trying to do is stop that thread immediatly from the main
Define "immediatel y". In answering please consider issues such
as threads that are blocked in kernel calls, such as receiving
data on a socket, as well as data integrity issues (e.g. what happens
if by "immediatel y" you mean "at the end of the current bytecode
instruction", and if that implies that you may have system
data structures that are corrupted?).
Didn't notice anything obvious in the docs like a 'kill' method or
similar. I don't necessarily want the main program to exit, just to
kill one or more threads.


Searching the list/newsgroup archives with Google will reveal
past discussions and possibly some useful responses.

-Peter
Jul 18 '05 #3
Aaron Bingham wrote:
There is no way to 'kill' a thread in Python. You will need to do
something like

def timedLoop():
while not done:
time.sleep(10)
doSomething()


See this recipe for an example using a threading.Event as the flag:
http://aspn.activestate.com/ASPN/Coo...n/Recipe/65448

Kent
Jul 18 '05 #4
JCM
Jerry Sievers <je***@jerrysie vers.com> wrote:
Greetings Pythonists; I have limited experience with threaded apps and plenty with old style
forked heavyweight multi-processing apps. Using Python 2.3.3 on a Redhat 7.x machine. Wondering if there is a simple way from a main python program to kill
a running thread?


Sort of. You can send a unix signal to the main thread (it causes an
exception which you can catch). But as others have and will surely
point out, it's usually better to have your thread occasionally check
whether it should die, so it doesn't leave anything in a bad state.
Jul 18 '05 #5
I might reiterate this request, but knowing the standard answer (you
can't) -- what if I *really* want to? In situations when a thread
becomes wedged, I don't know a way to get out of it. I don't even know
a way to end the process elegantly, instead I have to kill -9 the process.

Even if it messes things up and I have to restart the process at the
soonest possible time to clean up the problems, it would be nice to be
able to exit the process. As it is, the only robust way to deal with
the situation is to have a separate process that (at the original
process's request) will kill it, an assisted-suicide style. That's
awkward to handle.

This is an issue with long-running threaded servers (like Webware or
even Zope), where even in the face of bugs it's important to keep the
service up.

--
Ian Bicking / ia**@colorstudy .com / http://blog.ianbicking.org
Jul 18 '05 #6
Ian Bicking wrote:
I might reiterate this request, but knowing the standard answer (you
can't) -- what if I *really* want to?
It looks to me sort of as if you are actually reiterating the
request above... but then going ahead and answering your own
question. Is that what happened here? Because if it isn't,
I'm not sure what other answer one could give....
In situations when a thread
becomes wedged, I don't know a way to get out of it. I don't even know
a way to end the process elegantly, instead I have to kill -9 the process.

Even if it messes things up and I have to restart the process at the
soonest possible time to clean up the problems, it would be nice to be
able to exit the process. As it is, the only robust way to deal with
the situation is to have a separate process that (at the original
process's request) will kill it, an assisted-suicide style. That's
awkward to handle.

This is an issue with long-running threaded servers (like Webware or
even Zope), where even in the face of bugs it's important to keep the
service up.

Jul 18 '05 #7
Peter Hansen wrote:
Ian Bicking wrote:
I might reiterate this request, but knowing the standard answer (you
can't) -- what if I *really* want to?

It looks to me sort of as if you are actually reiterating the
request above... but then going ahead and answering your own
question. Is that what happened here? Because if it isn't,
I'm not sure what other answer one could give....


It's more, "yes, I know the answer, but I remain unsatisfied". I'm 100%
okay with a platform-specific way to accomplish this (especially if the
platform is Linux and BSD). I'm okay with horrid hacks, or memory
leaks, or other possible compromises. But I'm not really okay with the
standard answer. And so I'm hoping someone else felt the same way and
figured something out...?

--
Ian Bicking / ia**@colorstudy .com / http://blog.ianbicking.org
Jul 18 '05 #8
Ian Bicking <ia**@colorstud y.com> writes:
(...)
Even if it messes things up and I have to restart the process at the
soonest possible time to clean up the problems, it would be nice to be
able to exit the process. (...)


I'm not positive, but os._exit() may at least let you get the process
exited regardless of any thread states.

-- David
Jul 18 '05 #9
Ian Bicking <ia**@colorstud y.com> writes:
It's more, "yes, I know the answer, but I remain unsatisfied". I'm
100% okay with a platform-specific way to accomplish this (especially
if the platform is Linux and BSD). I'm okay with horrid hacks, or
memory leaks, or other possible compromises. But I'm not really okay
with the standard answer. And so I'm hoping someone else felt the
same way and figured something out...?


I'm not familiar enough with pthreads to guess there, but under
Windows, you can technically accomplish what you want using
TerminateThread . Perhaps there is a similar flow that could be used
with pthreads.

My major concern though in any attempt to externally kill off a thread
would be that you somehow strand the interpreter with that dead thread
still owning the GIL. There's plenty of other sorts of system
resources that could also be stranded (at least until process exit),
but killing off the GIL owner would definitely mess up the
application's day.

As a sample, the following works under Windows:

- - - - - - - - - - - - - - - - - - - - - - - - -

import threading
import ctypes
import time

w32 = ctypes.windll.k ernel32
THREAD_TERMINAT E = 1 # Privilege level for termination

class DummyThread(thr eading.Thread):

def __init__(self):
threading.Threa d.__init__(self )
self.setDaemon( 1)

def run(self):
self.tid = w32.GetCurrentT hreadId()

while 1:
print 'Running'
time.sleep(1)

def kill_thread(thr eadobj):

handle = w32.OpenThread( THREAD_TERMINAT E, False, threadobj.tid)
result = w32.TerminateTh read(handle, 0)
w32.CloseHandle (handle)

return result

if __name__ == "__main__":

print 'Starting thread...'
x = DummyThread()
x.start()

time.sleep(5)
print 'Terminating thread...'
kill_thread(x)

time.sleep(5)
print 'Exiting'

- - - - - - - - - - - - - - - - - - - - - - - - -

In DummyThread, a "self.get_ident ()" appears to return the native
platform thread id (so the same as the GetCurrentThrea dId() call), but
I didn't want to depend on that necessarily being the case.

Of course, while the above runs on my system, I do think it has a GIL
risk - I expect that ctypes is releasing the GIL just before calling
the native function, so there's a chance the other thread could resume
and obtain the GIL just prior to TerminateThread executing at the
Win32 layer. My odds are probably lower in this example since the
dummy thread is sleeping most of the time. So if I was going to use
this in practice I'd probably provide my own extension module that
wrapped TerminateThread but made sure *not* to release the GIL before
calling it.

Of course, there are other pieces of state that remained messed up,
particularly if you use the threading package as above - it still
thinks the thread is alive and would wait for it at process exit.
Setting it to a daemon works as above, but you could also get crufty
and just reach in and manually call the __stop and __delete methods of
the thread object (dealing with the name mangling).

Not sure I'd ever have the gumption to use this in practice unless my
very next step was to exit the process (in which case setting the
thread as daemon works just about as well), but it's technically
possible :-)

-- David

Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
12093
by: dcrespo | last post by:
Hi all, How can I get a raised exception from other thread that is in an imported module? For example: --------------- programA.py ---------------
6
42878
by: RickDee | last post by:
Understand that when I start a thread, a number will be generated and is able to get from GetHashCode method. But I would like to use this number when I want to kill certain thread, anybody know how ?? Thanks Regards
10
1428
by: Michael | last post by:
How do I kill the thread of one button with the clicking of another button? ie Private Sub btnEnglish_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnglish.Click System.Threading.Thread.Sleep(200) 'Do This
22
37748
by: Brett | last post by:
I have a second thread, t2, that errors out and will stop. It's status is then "Stopped". I try to start t2 from thread 1, t1, by checking If t2.threadstate = "Stopped" Then t2.start() However, this throws and error: System.Threading.ThreadStateException: Thread is running or terminated; it can not restart.
0
1199
by: Matt | last post by:
Ok so I'm creating this event scheduler in VB.NET with the use of threads. We would like the customer to be able to declare however many threads they want. For example... Lets say the user wants to be able to have 10 threads all running at the same time. Well I would need a way to dynamically created that number of threads at runtime and be able to control them all. Up until now I have been statically control the thread count so I...
51
54865
by: Hans | last post by:
Hi all, Is there a way that the program that created and started a thread also stops it. (My usage is a time-out). E.g. thread = threading.Thread(target=Loop.testLoop) thread.start() # This thread is expected to finish within a second
5
10600
by: care02 | last post by:
Hi! I have the following problem: I have written a short Python server that creates an indefinite simulation thread that I want to kill when quitting (Ctrl-C) from Python. Googling around has not given me any hints on how to cleanly kill running threads before exiting. Any help is appreciated! Carl
2
1938
by: Sjoerd Op 't Land | last post by:
Hello all, I'm using threading for generating video content. The trouble is how to kill the thread, because there are multiple (simultaneous) owners of a thread. Ideally, a flag would be set when the reference count of the thread becomes zero, causing the run() loop to quit. Example: import threading import time import gc
20
5097
by: =?ISO-8859-1?Q?Gerhard_H=E4ring?= | last post by:
John Dohn wrote: When I do this, I put a special value in the queue (like None) and in the worker thread, check for the special value and exit if found. Threads can also be marked as "daemon threads" (see docs for threading.Thread objects). This will make the application terminate if only "daemon threads" are left. So best would probably be soemthing like
0
10031
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9869
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9708
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8709
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7242
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5140
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3354
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2665
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.