473,769 Members | 5,823 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Stop a thread on deletion

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

class myThread(thread ing.Thread):
def __init__(self):
self.passedOut = threading.Event ()
threading.Threa d.__init__(self )
def __del__(self):
self.passedOut. set()
def run(self):
i = 0
while not self.passedOut. isSet():
i += 1
print "Hi %d" % i
time.sleep(0.25 )
a = myThread()
a.start()
time.sleep(2.5)
a = None
time.sleep(2.5)

Unfortunately, this doesn't work. When I remove the while-loop, __del__
is called, actually. Appearantly there is still some reference to the
thread while it is running.

I tried gc.get_referrer s(self), but it seems to need some parsing. I'm
not sure how to implement that and I'm not sure whether it will work
always or not.

Thanks in advance for any suggestion,
Sjoerd Op 't Land
Aug 8 '07 #1
2 1938
On 8/8/07, Sjoerd Op 't Land <sj****@intercu e.nlwrote:
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

class myThread(thread ing.Thread):
def __init__(self):
self.passedOut = threading.Event ()
threading.Threa d.__init__(self )
def __del__(self):
self.passedOut. set()
def run(self):
i = 0
while not self.passedOut. isSet():
i += 1
print "Hi %d" % i
time.sleep(0.25 )
a = myThread()
a.start()
time.sleep(2.5)
a = None
time.sleep(2.5)

Unfortunately, this doesn't work. When I remove the while-loop, __del__
is called, actually. Appearantly there is still some reference to the
thread while it is running.

I tried gc.get_referrer s(self), but it seems to need some parsing. I'm
not sure how to implement that and I'm not sure whether it will work
always or not.
gc.get_referrer s returns a list of object instances that hold a
reference to the object. The important one in this case is, of course,
the thread itself. The thread holds a reference to the run method
which (of course) requires a reference to the object. In other words,
a running thread cannot be refcounted to zero. You are going to need a
better method of handling your resources.

Perhaps instead of holding a reference to the thread, they could hold
a reference to a proxy object:

import threading
import time
import gc
import pprint

class myThread(thread ing.Thread):
def __init__(self):
self.passedOut = threading.Event ()
threading.Threa d.__init__(self )
def run(self):
i = 0
while not self.passedOut. isSet():
i += 1
print "Hi %d" % i
time.sleep(1)
print "stopped"
class ThreadProxy(obj ect):
def __init__(self, proxy_for):
self.proxy_for = proxy_for
def __del__(self):
self.proxy_for. passedOut.set()
def start(self):
self.proxy_for. start()
Aug 8 '07 #2
Dear Cris,

Thanks a lot. This works! (What you didn't know, there was already such
a 'proxy' object in the design, so it isn't the hack it looks ;).)

Thanks again,
Sjoerd Op 't Land

Chris Mellon schreef:
On 8/8/07, Sjoerd Op 't Land <sj****@intercu e.nlwrote:
>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

class myThread(thread ing.Thread):
def __init__(self):
self.passedOut = threading.Event ()
threading.Threa d.__init__(self )
def __del__(self):
self.passedOut. set()
def run(self):
i = 0
while not self.passedOut. isSet():
i += 1
print "Hi %d" % i
time.sleep(0.25 )
a = myThread()
a.start()
time.sleep(2.5 )
a = None
time.sleep(2.5 )

Unfortunatel y, this doesn't work. When I remove the while-loop, __del__
is called, actually. Appearantly there is still some reference to the
thread while it is running.

I tried gc.get_referrer s(self), but it seems to need some parsing. I'm
not sure how to implement that and I'm not sure whether it will work
always or not.

gc.get_referrer s returns a list of object instances that hold a
reference to the object. The important one in this case is, of course,
the thread itself. The thread holds a reference to the run method
which (of course) requires a reference to the object. In other words,
a running thread cannot be refcounted to zero. You are going to need a
better method of handling your resources.

Perhaps instead of holding a reference to the thread, they could hold
a reference to a proxy object:

import threading
import time
import gc
import pprint

class myThread(thread ing.Thread):
def __init__(self):
self.passedOut = threading.Event ()
threading.Threa d.__init__(self )
def run(self):
i = 0
while not self.passedOut. isSet():
i += 1
print "Hi %d" % i
time.sleep(1)
print "stopped"
class ThreadProxy(obj ect):
def __init__(self, proxy_for):
self.proxy_for = proxy_for
def __del__(self):
self.proxy_for. passedOut.set()
def start(self):
self.proxy_for. start()
Aug 8 '07 #3

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

Similar topics

9
2420
by: Harald Armin Massa | last post by:
I need to do some synchronisations like in a cron.job import time from threading import Thread class updater(Thread): def run(self): while True: do_updates() time.sleep(600)
1
363
by: Peter Steele | last post by:
Okay, I assume I'm missing something obvious here. I have created a simple service in C# that on starting spawns a thread to do some processing. The service can be stopped with a "net stop" command of course, but under some circumstances the service will decide to terminate itself. My OnStart looks something like this: protected override void OnStart(string args) { serviceThread = new Thread(new ThreadStart(ServiceThreadStart));...
3
1723
by: Niyazi | last post by:
Hi, I created application that I get information from AS400 for reporting. In main.exe has only 1 frm which calls (as a class library) CLS_MAIN.dll. The CLS_MAIN.dll get the tables from AS400 and stores it in Dataset. Then returns to main frm then main frm calls the FirstReport.dll. The FirstReport.dll get the information from access database and creates the sqkl string and works with dataset and then writes in pre-formated Excel sheet.
2
2861
by: Prasad | last post by:
Hi, I am writing a service which takes a long time to stop after the OnStop call is given by the Services Snap-in. The problem is I cannot cut down on the time that it takes to Stop. The Service snap-in gives me the error saying that the service did not respond to the Stop call in a timely fashion. So is there any method by which I can get around this problem. Thanks Prasad
8
2311
by: Tim Bücker | last post by:
Following scenario: The user opens a form, a thread is started to play a sound ... public void playSoundUsingThread() { if (File.Exists(fileLocation)) PlaySound(fileLocation, 0, 0); // winmm.dll }
26
4701
by: Ricardo | last post by:
I made a program that generate random numbers and put it in a listbox when the user click go. The problem is: how can i made a button stop, to stop the method that is running??? s...
3
5766
by: Saizan | last post by:
I embedded an Rpyc threaded server in a preexistent daemon (an irc bot), this is actually very simple; start_threaded_server(port = DEFAULT_PORT) then I had the necessity to stop the thread which accept() new connections without killing the whole app, the thread is simply a while True that spawn a new thread which serves each connection, so I placed a flag and a break in this way: def local_threaded_server(port = DEFAULT_PORT, **kw):...
9
4000
by: Jon Slaughter | last post by:
I'm using Thread and ThreadStart to create a thread for testing purposes and I do not want to use a pool because the thread exists for the life time of the app. Eventually I might move on to using pools but at this point I'm just testing some timing issues. in any cause the thread is simply a counter, static void counter()
0
1326
by: =?Utf-8?B?anAybXNmdA==?= | last post by:
I have a windows application that does not stop running whenever the application exits. Could someone fill me in on what I am doing wrong? Here is the relevant code: ================================= Private m_thTCP As Thread Private m_listener As TcpListener
0
9586
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
9423
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
10210
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
10043
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...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9861
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
8869
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
5298
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...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.