weakrefs, threads,, and object ids

J

Jeremy

Hello,

I'm using weakrefs in a small multi-threaded application. I have been
using object IDs as dictionary keys with weakrefs to execute removal
code, and was glad to find out that this is in fact recommended
practice (http://docs.python.org/library/weakref.html)
This simple example shows how an application can use objects IDs to retrieve
objects that it has seen before. The IDs of the objects can then be used in other
data structures without forcing the objects to remain alive, but the objects can
still be retrieved by ID if they do.

After reading this, I realized it made no explicit mention of thread
safety in this section, whereas other sections made a note of correct
practice with threads. The docs for the id() function specify
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)

While guaranteed unique for simultaneously existing objects, how often
will an object assume an ID previously held by former object? Given
that the ID is a memory address in Python's heap, I assume the answer
is either not often, or very often.

Specifically, I'm wondering if the case can occur that the callback
for a weakref is executed after another object has been allocated with
the same object identifier as a previous object. If such an object is
inserted into a module-level dictionary, could it over-write a
previous entry with the same identifier and then get deleted whenever
the weakref callback happens to fire?



On a related note, what is a recommended way to obtain a weak
reference to a thread?
 
A

Aahz

While guaranteed unique for simultaneously existing objects, how often
will an object assume an ID previously held by former object? Given
that the ID is a memory address in Python's heap, I assume the answer
is either not often, or very often.

Very often:

Python 2.4 (#1, Jan 17 2005, 14:59:14)
[GCC 3.3.3 (NetBSD nb3 20040520)] on netbsd2
Type "help", "copyright", "credits" or "license" for more information.True

Sorry, can't help you with your other questions; I'm not familiar with
weakrefs.
--
Aahz ([email protected]) <*> http://www.pythoncraft.com/

"Many customs in this life persist because they ease friction and promote
productivity as a result of universal agreement, and whether they are
precisely the optimal choices is much less important." --Henry Spencer
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top