Counting number of objects
Kottiyath
n.kottiyath at gmail.com
Tue Jan 27 04:17:33 EST 2009
Thank you everyone for your very helpful comments and suggestions. I
have interacted in other newsgroups, but this is the most helpful of
them all.
As per the comments, I have now decided to go with the weakref
mechanism - as per Andreas suggestion, functionally it looks correct
that the person should not know the total number of people.
So, in a higher level class, have a weakref list which contains a
reference to each person. Total count will be len(list) at any time.
Now, I couldnt find a weakref list - so I am using WeakKeyDictionary
with the value as None - since len(dict) also should give me the data
any time.
I have another question here. In the documentation, it is mentioned
that -
Note: Caution: Because a WeakKeyDictionary is built on top of a Python
dictionary, it must not change size when iterating over it. This can
be difficult to ensure for a WeakKeyDictionary because actions
performed by the program during iteration may cause items in the
dictionary to vanish "by magic" (as a side effect of garbage
collection).
Now, the only two operations that I am doing are ->
__init__:
d = weakref.WeakKeyDictionary()
method y:
x = aa()
d[x] = None
method z:
total = len(d)
I believe that all the commands which I perform on WeakKeyDictionary
here - (adding a new element) & (len(d)) - are atomic - or atleast
nothing that can cause any worry as per the Note given above. Can
anyone let me know whether my assumption is correct or not?
Reason: My code has many many number of threads which interact with
each other in myraid ways - so I do want to decrease the number of
locks as much as possible. Especially I do not want to block other
threads just for getting the count.
More information about the Python-list
mailing list