473,230 Members | 1,867 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,230 software developers and data experts.

Threading-> Stopping

Is there a way to stop a thread with some command like t.stop()? Or any
other neat way to get around it? Thanks!

Nov 4 '05 #1
5 8524
Tuvas wrote:
Is there a way to stop a thread with some command like t.stop()? Or any
other neat way to get around it? Thanks!


Sadly, no. While Java and many other programming languages have an
interrupt() primitive, Python does not. You can approximate this by
using a global variable to tell the thread when to stop, for example:

shutdown = False

class MyThread(Thread):
def run(self):
while not shutdown:
# do whatever

def kill_thread():
shutdown = True

There's no general way to wake up a thread that's blocked--you have to
satisfy the condition that's causing it to block. If it's waiting for
input from a Queue, you have to push a dummy value down it to wake up
the thread and give it a chance to check the shutdown flag. If it's
blocking to do I/O, you'll have to use select() and provide a timeout
value to check the flag periodically.

-- David

Nov 4 '05 #2
Thanks!

Nov 4 '05 #3
Op 2005-11-04, Tuvas schreef <tu*****@gmail.com>:
Is there a way to stop a thread with some command like t.stop()? Or any
other neat way to get around it? Thanks!


What do you mean with stop? Pauze it or make it finish.

In the latter case, if you really want it you could use the following.
It requires ctypes. It also wont stop a thread while it is in a C
extention. In that case the exception will be raised when it returns
from the extention.

import os
import ctypes
from time import sleep
from random import randint
class TimeOut(Exception):
pass

class Alarm(Exception):
pass

import threading

class Xthread(threading.Thread):

def start(self):
self.__original_run = self.run
self.run = self.__run
threading.Thread.start(self)

def __run(self):
self.__thrd_id = threading._get_ident()
try:
self.__original_run()
finally:
self.run = self.__original_run

def raize(self, excpt):
Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__ thrd_id, ctypes.py_object(excpt))
while Nr > 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__ thrd_id, None)
sleep(0.1)
Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__ thrd_id, ctypes.py_object(excpt))

def alarm(self, tm):
alrm = threading.Timer(tm, self.raize, (TimeOut,))
alrm.start()
return alrm

if __name__ == "__main__":

class Continue(Xthread):

def run(self):

self.id = os.getpid()
print self.id, "Begin"
i = 0
try:
for _ in xrange(randint(0,20)):
for e in xrange(4 * 100000):
i = i + e
print self.id, "Finished"
except Alarm:
print self.id, "Interupted"

lst = [Continue() for _ in xrange(10)]

for T in lst:
T.start()

try:
sleep(10)
finally:
for T in lst:
T.raize(Alarm)
Nov 7 '05 #4
[Tuvas]
Is there a way to stop a thread with some command like t.stop()? Or any
other neat way to get around it? Thanks!


Good question.

And one that gets asked so often, I ask myself why it isn't in the FAQ?

http://www.python.org/doc/faq/library.html

It really should be in the FAQ. Isn't that what FAQs are for?

Maybe the FAQ needs to be turned into a wiki?

--
alan kennedy
------------------------------------------------------
email alan: http://xhaus.com/contact/alan
Nov 7 '05 #5
On Mon, 07 Nov 2005 13:49:35 +0000, Alan Kennedy <al****@hotmail.com> wrote:
[Tuvas]
Is there a way to stop a thread with some command like t.stop()? Or any
other neat way to get around it? Thanks!


Good question.

And one that gets asked so often, I ask myself why it isn't in the FAQ?

http://www.python.org/doc/faq/library.html

It really should be in the FAQ. Isn't that what FAQs are for?

Maybe the FAQ needs to be turned into a wiki?

Maybe when really good answers to questions get posted, we could edit it
down to a final version candidate that we all agree on, and when agreed,
make the final post with a tag line that google will recognize and that
can be a tag line for python newsgroup gems.

Sort of like a wiki-within-newsgroup in effect. E.g., "Tim Peters" site:python.org
gets a lot of interesting stuff. Likewise Martelli, though the volume is daunting
either way (140,000 & 32,400 resp ;-)

What about "python-newsgroup-faq" site:python.org? If we avoid the tag line in all but
finalized posts, that plus some additional search-narrowing via google would probably
be pretty effective. But this is a social engineering problem more than technical ;-)

BTW, would such a thing appropriately be defined in a process PEP?

Regards,
Bengt Richter
Nov 7 '05 #6

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

Similar topics

65
by: Anthony_Barker | last post by:
I have been reading a book about the evolution of the Basic programming language. The author states that Basic - particularly Microsoft's version is full of compromises which crept in along the...
2
by: Egor Bolonev | last post by:
hi all my program terminates with error i dont know why it tells 'TypeError: run() takes exactly 1 argument (10 given)' =program==================== import os, os.path, threading, sys def...
77
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for...
6
by: CK | last post by:
I have the following code in a windows service, when I start the windows service process1 and process2 work fine , but final process (3) doesnt get called. i stop and restart the windows service...
2
by: Vjay77 | last post by:
In this code: Private Sub downloadBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) If Not (Me.downloadUrlTextBox.Text = "") Then Me.outputGroupBox.Enabled = True...
11
by: Paul Sijben | last post by:
I am stumped by the following problem. I have a large multi-threaded server accepting communications on one UDP port (chosen for its supposed speed). I have been profiling the code and found...
17
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. ...
0
by: kingcrowbar.list | last post by:
Hello Everyone I have been playing a little with pyGTK and threading to come up with simple alert dialog which plays a sound in the background. The need for threading came when in the first...
2
by: Daniel | last post by:
I have a class similar to this: class MyThread(threading.Thread): def __init__(self): self.terminated = False def run(self): while not self.terminated:
7
by: Mike P | last post by:
I am trying to write my first program using threading..basically I am moving messages from an Outlook inbox and want to show the user where the process is up to without having to wait until it has...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 3 Jan 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). For other local times, please check World Time Buddy In...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.