473,746 Members | 2,667 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to force a thread to stop

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.Threa d(target=Loop.t estLoop)
thread.start() # This thread is expected to finish within a second
thread.join(2) # Or time.sleep(2) ?

if thread.isAlive( ):
# thread has probably encountered a problem and hangs
# What should be here to stop thread ??????

Note that I don't want to change the target (too much), as many possible
targets exist,
together thousands of lines of code.

Thanks,
Hans
Jul 22 '06 #1
51 54858

Hans wrote:
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.Threa d(target=Loop.t estLoop)
thread.start() # This thread is expected to finish within a second
thread.join(2) # Or time.sleep(2) ?
No, Python has no threadicide method, and its absence is not an
oversight. Threads often have important business left to do, such
as releasing locks on shared data; killing them at arbitrary times
tends to leave the system in an inconsistent state.
if thread.isAlive( ):
# thread has probably encountered a problem and hangs
# What should be here to stop thread ??????
At this point, it's too late. Try to code so your threads don't hang.

Python does let you arrange for threads to die when you want to
terminate the program, with threading's Thread.setDaemo n().
--
--Bryan

Jul 22 '06 #2
Hi!
>> "threadicid e" method
I like this word...

Michel Claveau
Jul 23 '06 #3
In message <11************ **********@m73g 2000cwd.googleg roups.com>,
br************* **********@yaho o.com wrote:
Python has no threadicide method, and its absence is not an
oversight. Threads often have important business left to do, such
as releasing locks on shared data; killing them at arbitrary times
tends to leave the system in an inconsistent state.
Perhaps another reason to avoid threads and use processes instead?
Jul 24 '06 #4
Lawrence D'Oliveiro <ld*@geek-central.gen.new _zealandwrites:
Python has no threadicide method, and its absence is not an
oversight. Threads often have important business left to do, such
as releasing locks on shared data; killing them at arbitrary times
tends to leave the system in an inconsistent state.

Perhaps another reason to avoid threads and use processes instead?
If the processes are sharing resources, the exact same problems arise.
Jul 24 '06 #5
Dennis Lee Bieber wrote:
On Sat, 22 Jul 2006 14:47:30 +0200, "Hans" <No****@Hccnet. nldeclaimed
the following in comp.lang.pytho n:

>Hi all,

Is there a way that the program that created and started a thread also stops
it.
(My usage is a time-out).

Hasn't this subject become a FAQ entry yet? <G>

The only reliable way of stopping a thread is from inside the thread
itself. That is, the thread must, at some point, examine some flag
variable which, when set, says "stop"

Without using actual code:

class StoppableThread (...):
def __init__(self, ...):
#whatever is needed to initialize as a thread
self.Stop = False

def run(self, ...):
while not self.Stop:
#do one cycle of the computation
My problem with the fact that python doesn't have some type of "thread
killer" is that again, the only solution involves some type of polling
loop. I.e. "if your thread of execution can be written so that it
periodically checks for a kill condition". This really sucks, not just
because polling is a ridiculous practice, but it forces programmers in
many situations to go through a lengthy process of organizing operations
into a list. For, say I have threads that share a bunch of common
memory (yea, i'm saying this exclusively to get the procses users off my
back) that executes a series of commands on remote nodes using rsh or
something. So if i've constructed my system using threads I need to
neatly go and dump all operations into some sort of list so that I can
implement a polling mechanism, i.e.

opList = [op1, op2, op3, op4]
for op in opList:
checkMessageQue ue()
op()

That works if you can easily create an opList. If you want good
response time this can become quite ugly, especially if you have a lot
going on. Say I have a function I want to run in a thread:

#Just pretend for the sake of arguement that 'op' actually means
something and is a lengthy operation
def func_to_thread( ):
os.system('op 1')
os.system('op 2')
os.system('op 3')
#In order to make this killable with reasonable response time we have to
organize each of our ops into a function or something equally annoying

op_1():
os.system('op 1')

op_2():
os.system('op 2')

op_3():
os.system('op 3')

opList(op_1, op_2, op_3)
def to_thread():
for op in opList:
checkMessageQue ue()
op()
So with this whole "hey mr. nice thread, please die for me" concept gets
ugly quickly in complex situations and doesn't scale well at all.
Furthermore, say you have a complex systems where users can write
pluggable modules. IF a module gets stuck inside of some screwed up
loop and is unable to poll for messages there's no way to kill the
module without killing the whole system. Any of you guys thought of a
way around this scenario?
--

Carl J. Van Arsdall
cv*********@mvi sta.com
Build and Release
MontaVista Software

Jul 24 '06 #6
Carl J. Van Arsdall wrote:
[... rant ...]
So with this whole "hey mr. nice thread, please die for me" concept gets
ugly quickly in complex situations and doesn't scale well at all.
Furthermore, say you have a complex systems where users can write
pluggable modules. IF a module gets stuck inside of some screwed up
loop and is unable to poll for messages there's no way to kill the
module without killing the whole system. Any of you guys thought of a
way around this scenario?

Communications through Queue.Queue objects can help. But if you research
the history of this design decision in the language you should discover
there are fairly sound rasons for not allowing arbitrary "threadicid e".

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

Jul 24 '06 #7
Steve Holden wrote:
Carl J. Van Arsdall wrote:
[... rant ...]
>So with this whole "hey mr. nice thread, please die for me" concept gets
ugly quickly in complex situations and doesn't scale well at all.
Furthermore, say you have a complex systems where users can write
pluggable modules. IF a module gets stuck inside of some screwed up
loop and is unable to poll for messages there's no way to kill the
module without killing the whole system. Any of you guys thought of a
way around this scenario?

Communications through Queue.Queue objects can help. But if you research
the history of this design decision in the language you should discover
there are fairly sound rasons for not allowing arbitrary "threadicid e".
Right, I'm wondering if there was a way to make an interrupt driven
communication mechanism for threads? Example: thread receives a
message, stops everything, and processes the message.
--

Carl J. Van Arsdall
cv*********@mvi sta.com
Build and Release
MontaVista Software

Jul 24 '06 #8
"Carl J. Van Arsdall" <cv*********@mv ista.comwrites:
Communications through Queue.Queue objects can help. But if you
research the history of this design decision in the language you
should discover there are fairly sound rasons for not allowing
arbitrary "threadicid e".
Right, I'm wondering if there was a way to make an interrupt driven
communication mechanism for threads? Example: thread receives a
message, stops everything, and processes the message. --
There is in fact some under-the-covers mechanism in CPython (i.e.
one you can call from C extensions but not from Python code) to
raise exceptions in other threads. I've forgotten the details.
There has been discussion at various times about how to expose
something like that to Python code, but it's been inconclusive. E.g.:

http://sf.net/tracker/?func=detail&a...&group_id=5470
Jul 25 '06 #9

Carl J. Van Arsdall wrote:
[...]
My problem with the fact that python doesn't have some type of "thread
killer" is that again, the only solution involves some type of polling
loop.
A polliing loop is neither required nor helpful here.

[...]
#Just pretend for the sake of arguement that 'op' actually means
something and is a lengthy operation
def func_to_thread( ):
os.system('op 1')
os.system('op 2')
os.system('op 3')
What good do you think killing that thread would do? The
process running 'op n' has no particular binding to the thread
that called os.system(). If 'op n' hangs, it stays hung.

The problem here is that os.system doesn't give you enough
control. It doesn't have a timeout and doesn't give you a
process ID or handle to the spawned process.

Running os.system() in multiple threads strikes me as
kind of whacked. Won't they all compete to read and write
stdin/stdout simultaneously?
#In order to make this killable with reasonable response time we have to
organize each of our ops into a function or something equally annoying

op_1():
os.system('op 1')

op_2():
os.system('op 2')

op_3():
os.system('op 3')

opList(op_1, op_2, op_3)
def to_thread():
for op in opList:
checkMessageQue ue()
op()
Nonsense. If op() hangs, you never get to checkMessageQue ue().

Now suppose op has a timeout. We could write

def opcheck(thing):
result = op(thing)
if result == there_was_a_tim eout:
raise some_timeout_ex ception

How is:

def func_to_thread( ):
opcheck('op 1')
opcheck('op 2')
opcheck('op 3')

any less managable than your version of func_to_thread?
So with this whole "hey mr. nice thread, please die for me" concept gets
ugly quickly in complex situations and doesn't scale well at all.
Furthermore, say you have a complex systems where users can write
pluggable modules. IF a module gets stuck inside of some screwed up
loop and is unable to poll for messages there's no way to kill the
module without killing the whole system. Any of you guys thought of a
way around this scenario?
Threadicide would not solve the problems you actually have, and it
tends to create other problems. What is the condition that makes
you want to kill the thread? Make the victim thread respond to that
condition itself.
--
--Bryan

Jul 25 '06 #10

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

Similar topics

2
2411
by: Olivier Parisy | last post by:
Hi, I like to use thread to simplify the handling of independant, blocking tasks. But controling them from a main thread is not always easy to do in a clean way. So I've written some generic code whose purpose is to start and stop threads in a synchronous (blocking) way from the caller's point of view. Hence, after start() is called you are garanteed that the thread is running, and after stop() you know it has completed
13
3492
by: Andy Fish | last post by:
Hi, I am using COM interop to invoke MS word from my .net app. If word pops up a dialog box, my thread obviously hangs until the dialog is answered. Here's the problem: because the app is running on a server, there is nobody there to answer the dialog, so I have another thread that calls Abort() on the first thread in the event that the operation doesn't complete within a certain amount of time.
16
6731
by: LP | last post by:
Hi, Considering code below. Will it make GC to actually collect. One application creates new instances of a class from 3rd party assembly in a loop (it has to). That class doesn't have .Dispose or any similar method. I want to make sure GC keeps up with the loop. My reasoning if Thread.Sleep(1000) is called; GC will take priority it do its work, right? GC.Collect(); GC.WaitForPendingFinalizers(); System.Threading.Thread.Sleep(1000);
4
2558
by: fred | last post by:
I use a Synclock in a secondary thread and also stop the thread using the abort method. If the abort occurs while the thread is in the Synclock will the SyncLock always be released before the thread stops or do I need to add some extra code to avoid Synclock staying on after the thread has been stopped. Thanks Fred
4
7018
by: kaiteriteri | last post by:
I have a time-consuming VB.net application that i'd like to thread over 2 processors (that's all i've got in my machine!) and, hopefully, get it done in half the time. On running, the application should create a 2nd thread and run it on the other processor (processing a distinct set of data), leaving the current thread to run and process its set of data. But the 2nd thread must run on the free processor, otherwise there's no point... ...
6
5992
by: Joe Jax | last post by:
I have an object that spawns a worker thread to process one of its methods. That method processes methods on a collection of other objects. During this processing, a user may request to cancel the entire operation. I could request abort on the worker thread, but that is a) potentially messy, and b) not guaranteed to take immediate effect anyway. I would rather have some way of allowing the main thread to tell the worker thread that it...
5
2805
by: Alan T | last post by:
I will do several things in my thread: Copy a file to a location Update database record Read the file content Write the content to a log file If I call Thread.Abort(), it may be possible to stop at the middle of the something ?
3
3180
by: yeye.yang | last post by:
hey everybody Does everybody can help me or give me some advise for the cross thread exception catch Here is what I want to do: I have 2 classes "Scenario" and "Step", which have a System.Thread.Timer for each to control their timeout gestion, in my "main program", I start the "Scenario" and "Step", and I do something between "StepStart" and "StepStop", when "Scenario" or "Step" timeout expired, they raise an "exception", then my "main...
1
2534
by: raghudr | last post by:
Hi all, I am displaying a splash screen for which i have created a thread.Since my whole project is launched by windows service and that service will start automatically at the start of the PC and sometimes when i start or restart the PC i have observed that even though the long process is completed splash
0
8974
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8800
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9500
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
9349
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
8227
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...
0
6060
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
4575
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...
1
3292
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2765
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.