473,621 Members | 2,745 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confusion with weakref, __del__ and threading

I'm baffled with a situation that involves:
1) an instance of some class that defines __del__,
2) a thread which is created, started and referenced by that instance,
and
3) a weakref proxy to the instance that is passed to the thread
instead of 'self', to prevent a cyclic reference.

This probably sounds like gibberish so here's a simplified example:

=============== =============== ============

import time
import weakref
import threading

num_main = num_other = 0
main_thread = threading.curre ntThread()
class Mystery(object) :

def __init__(self):
proxy = weakref.proxy(s elf)
self._thread = threading.Threa d(target=target , args=(proxy,))
self._thread.st art()

def __del__(self):
global num_main, num_other
if threading.curre ntThread() is main_thread:
num_main += 1
else:
num_other += 1

def sleep(self, t):
time.sleep(t)
def target(proxy):
try: proxy.sleep(0.0 1)
except weakref.Referen ceError: pass
if __name__ == '__main__':
for i in xrange(1000):
Mystery()
time.sleep(0.1)
print '%d __del__ from main thread' % num_main
print '%d __del__ from other threads' % num_other

=============== =============== ============

When I run it, I get around 950 __del__ from the main thread and the
rest from non-main threads. I discovered this accidentally when I
noticed some ignored AssertionErrors caused by a __del__ that was
doing "self._thread.j oin()", assuming that the current thread is not
self._thread, but as it turns out that's not always the case.

So what is happening here for these ~50 minority cases ? Is __del__
invoked through the proxy ?

George
Jun 27 '08 #1
6 2859
On Jun 10, 8:15 pm, George Sakkis <george.sak...@ gmail.comwrote:
I'm baffled with a situation that involves:
1) an instance of some class that defines __del__,
2) a thread which is created, started and referenced by that instance,
and
3) a weakref proxy to the instance that is passed to the thread
instead of 'self', to prevent a cyclic reference.

This probably sounds like gibberish so here's a simplified example:

=============== =============== ============

import time
import weakref
import threading

num_main = num_other = 0
main_thread = threading.curre ntThread()

class Mystery(object) :

def __init__(self):
proxy = weakref.proxy(s elf)
self._thread = threading.Threa d(target=target , args=(proxy,))
self._thread.st art()

def __del__(self):
global num_main, num_other
if threading.curre ntThread() is main_thread:
num_main += 1
else:
num_other += 1

def sleep(self, t):
time.sleep(t)

def target(proxy):
try: proxy.sleep(0.0 1)
except weakref.Referen ceError: pass

if __name__ == '__main__':
for i in xrange(1000):
Mystery()
time.sleep(0.1)
print '%d __del__ from main thread' % num_main
print '%d __del__ from other threads' % num_other

=============== =============== ============

When I run it, I get around 950 __del__ from the main thread and the
rest from non-main threads. I discovered this accidentally when I
noticed some ignored AssertionErrors caused by a __del__ that was
doing "self._thread.j oin()", assuming that the current thread is not
self._thread, but as it turns out that's not always the case.

So what is happening here for these ~50 minority cases ? Is __del__
invoked through the proxy ?
The trick here is that calling proxy.sleep(0.0 1) first gets a strong
reference to the Mystery instance, then holds that strong reference
until it returns.

If the child thread gets the GIL before __init__ returns it will enter
Mystery.sleep, then the main thread will return from Mystery.__init_ _
and release its strong reference, followed by the child thread
returning from Mystery.sleep, releasing its strong reference, and (as
it just released the last strong reference) calling Mystery.__del__ .

If the main thread returns from __init__ before the child thread gets
the GIL, it will release the only strong reference to the Mystery
instance, causing it to clear the weakref proxy and call __del__
before the child thread ever gets a chance. If you added counters to
the target function you should see them match the counters of the
__del__ function.

Incidentally, += 1 isn't atomic in Python. It is possible for updates
to be missed.
Jun 27 '08 #2
On Jun 11, 1:40 am, Rhamphoryncus <rha...@gmail.c omwrote:
On Jun 10, 8:15 pm, George Sakkis <george.sak...@ gmail.comwrote:
I'm baffled with a situation that involves:
1) an instance of some class that defines __del__,
2) a thread which is created, started and referenced by that instance,
and
3) a weakref proxy to the instance that is passed to the thread
instead of 'self', to prevent a cyclic reference.
This probably sounds like gibberish so here's a simplified example:
=============== =============== ============
import time
import weakref
import threading
num_main = num_other = 0
main_thread = threading.curre ntThread()
class Mystery(object) :
def __init__(self):
proxy = weakref.proxy(s elf)
self._thread = threading.Threa d(target=target , args=(proxy,))
self._thread.st art()
def __del__(self):
global num_main, num_other
if threading.curre ntThread() is main_thread:
num_main += 1
else:
num_other += 1
def sleep(self, t):
time.sleep(t)
def target(proxy):
try: proxy.sleep(0.0 1)
except weakref.Referen ceError: pass
if __name__ == '__main__':
for i in xrange(1000):
Mystery()
time.sleep(0.1)
print '%d __del__ from main thread' % num_main
print '%d __del__ from other threads' % num_other
=============== =============== ============
When I run it, I get around 950 __del__ from the main thread and the
rest from non-main threads. I discovered this accidentally when I
noticed some ignored AssertionErrors caused by a __del__ that was
doing "self._thread.j oin()", assuming that the current thread is not
self._thread, but as it turns out that's not always the case.
So what is happening here for these ~50 minority cases ? Is __del__
invoked through the proxy ?

The trick here is that calling proxy.sleep(0.0 1) first gets a strong
reference to the Mystery instance, then holds that strong reference
until it returns.
Ah, that was the missing part; I thought that anything accessed
through a proxy didn't create a strong reference. The good thing is
that it seems you can get a proxy to a bounded method and then call it
without creating a strong reference to 'self':

num_main = num_other = 0
main_thread = threading.curre ntThread()

class MysterySolved(o bject):

def __init__(self):
sleep = weakref.proxy(s elf.sleep)
self._thread = threading.Threa d(target=target , args=(sleep,))
self._thread.st art()

def __del__(self):
global num_main, num_other
if threading.curre ntThread() is main_thread:
num_main += 1
else:
num_other += 1

def sleep(self, t):
time.sleep(t)
def target(sleep):
try: sleep(0.01)
except weakref.Referen ceError: pass
if __name__ == '__main__':
for i in xrange(1000):
MysterySolved()
time.sleep(.1)
print '%d __del__ from main thread' % num_main
print '%d __del__ from other threads' % num_other

=============== =============== ============
Output:
1000 __del__ from main thread
0 __del__ from other threads
Thanks a lot, I learned something new :)

George
Jun 27 '08 #3
On Jun 11, 10:43 am, George Sakkis <george.sak...@ gmail.comwrote:
On Jun 11, 1:40 am, Rhamphoryncus <rha...@gmail.c omwrote:
The trick here is that calling proxy.sleep(0.0 1) first gets a strong
reference to the Mystery instance, then holds that strong reference
until it returns.

Ah, that was the missing part; I thought that anything accessed
through a proxy didn't create a strong reference. The good thing is
that it seems you can get a proxy to a bounded method and then call it
without creating a strong reference to 'self':
That's not right. Of course a bound method has a strong reference to
self, otherwise you'd never be able to call it. There must be
something else going on here. Try using sys.setcheckint erval(1) to
make threads switch more often.

>
num_main = num_other = 0
main_thread = threading.curre ntThread()

class MysterySolved(o bject):

def __init__(self):
sleep = weakref.proxy(s elf.sleep)
self._thread = threading.Threa d(target=target , args=(sleep,))
self._thread.st art()

def __del__(self):
global num_main, num_other
if threading.curre ntThread() is main_thread:
num_main += 1
else:
num_other += 1

def sleep(self, t):
time.sleep(t)

def target(sleep):
try: sleep(0.01)
except weakref.Referen ceError: pass

if __name__ == '__main__':
for i in xrange(1000):
MysterySolved()
time.sleep(.1)
print '%d __del__ from main thread' % num_main
print '%d __del__ from other threads' % num_other

=============== =============== ============
Output:
1000 __del__ from main thread
0 __del__ from other threads

Thanks a lot, I learned something new :)

George
Jun 27 '08 #4
On Jun 11, 2:01 pm, Rhamphoryncus <rha...@gmail.c omwrote:
On Jun 11, 10:43 am, George Sakkis <george.sak...@ gmail.comwrote:
On Jun 11, 1:40 am, Rhamphoryncus <rha...@gmail.c omwrote:
The trick here is that calling proxy.sleep(0.0 1) first gets a strong
reference to the Mystery instance, then holds that strong reference
until it returns.
Ah, that was the missing part; I thought that anything accessed
through a proxy didn't create a strong reference. The good thing is
that it seems you can get a proxy to a bounded method and then call it
without creating a strong reference to 'self':

That's not right. Of course a bound method has a strong reference to
self, otherwise you'd never be able to call it. There must be
something else going on here. Try using sys.setcheckint erval(1) to
make threads switch more often.
I tried that and it still works; all objects die at the main thread.
Any other idea to break it ?

George
Jun 27 '08 #5
On Jun 11, 2:15 pm, George Sakkis <george.sak...@ gmail.comwrote:
On Jun 11, 2:01 pm, Rhamphoryncus <rha...@gmail.c omwrote:
On Jun 11, 10:43 am, George Sakkis <george.sak...@ gmail.comwrote:
On Jun 11, 1:40 am, Rhamphoryncus <rha...@gmail.c omwrote:
The trick here is that calling proxy.sleep(0.0 1) first gets a strong
reference to the Mystery instance, then holds that strong reference
until it returns.
Ah, that was the missing part; I thought that anything accessed
through a proxy didn't create a strong reference. The good thing is
that it seems you can get a proxy to a bounded method and then call it
without creating a strong reference to 'self':
That's not right. Of course a bound method has a strong reference to
self, otherwise you'd never be able to call it. There must be
something else going on here. Try using sys.setcheckint erval(1) to
make threads switch more often.

I tried that and it still works; all objects die at the main thread.
Any other idea to break it ?
Nothing comes to mind.

However, none of this is guaranteed anyway, so you can't rely on it.
__del__ might be called by any thread at any point (even when you're
holding a lock, updating a datastructure.)
Jun 27 '08 #6
On Jun 11, 8:37*pm, Rhamphoryncus <rha...@gmail.c omwrote:
On Jun 11, 2:15 pm, George Sakkis <george.sak...@ gmail.comwrote:
On Jun 11, 2:01 pm, Rhamphoryncus <rha...@gmail.c omwrote:
On Jun 11, 10:43 am, George Sakkis <george.sak...@ gmail.comwrote:
On Jun 11, 1:40 am, Rhamphoryncus <rha...@gmail.c omwrote:
The trick here is that calling proxy.sleep(0.0 1) first gets a strong
reference to the Mystery instance, then holds that strong reference
until it returns.
Ah, that was the missing part; I thought that anything accessed
through a proxy didn't create a strong reference. The good thing is
that it seems you can get a proxy to a bounded method and then call it
without creating a strong reference to 'self':
That's not right. *Of course a bound method has a strong reference to
self, otherwise you'd never be able to call it. *There must be
something else going on here. *Try using sys.setcheckint erval(1) to
make threads switch more often.
I tried that and it still works; all objects die at the main thread.
Any other idea to break it ?

Nothing comes to mind.

However, none of this is guaranteed anyway, so you can't rely on it.
__del__ might be called by any thread at any point (even when you're
holding a lock, updating a datastructure.)
Ok, you scared me enough to cut the link to the thread altogether,
avoiding the cyclic reference and the weakref proxy. The original
intent for keeping a reference to the thread was to be able to join()
it later before some cleanup takes place. I have since found a less
spooky way to synchronize them but regardless, I'd be interested for
an explanation of what's really going on in the posted snippets.

George
Jun 27 '08 #7

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

Similar topics

1
2618
by: Ames Andreas (MPA/DF) | last post by:
Hi all, I'm using python 2.1 and can't easily upgrade (Zope). I'm using the Queue module to synchronize/communicate between two threads and weakref.proxy objects to avoid cycles. Scenario: thread1: - is the sole consumer (non-blocking get) - holds the reference to the queue
1
1989
by: Mathias Mamsch | last post by:
Hi, I have some confusion concerning the weakref module. I am trying to save a weak reference to a bound member function of a class instance for using it as a callback function. But I always get dead references, when I try to create a reference to a bound member function. It seems as if an instance of a class owns no reference to its memberfunctions, so the the reference count is always zero. How can I come behind that?
2
2076
by: Mike C. Fletcher | last post by:
I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate __del__ methods (and the memory leaks they create). Looking at the docs for 2.3's weakref.ref, there's no mention of whether the callbacks are held with a strong reference. My experiments suggest they are not... i.e. I'm trying to use this pattern: class Closer( object ): """Close the OIDStore (without a __del__)""" def __init__( self, btree ): """Initialise the...
1
1476
by: Erwan Adam | last post by:
Hello all, Can someone reproduce this bug ... I use : python Python 2.4.3 (#2, Sep 18 2006, 21:07:35) on linux2 Type "help", "copyright", "credits" or "license" for more information. First test :
0
8213
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
8156
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
8653
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...
1
8306
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
7127
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
5554
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
4150
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2587
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
1460
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.