Emanuele D'Arrigo schrieb:
Hi everybody,

Assuming a snippet such as:

threadLocalData = threading.local()
threadLocalData.myDictionary = self.myDictionary

is it correct to say that threadLocalData.myDictionary is NOT a thread-
local -copy- of self.myDictionary but it's actually pointing to the
same object?

Yes, it's pointing to the same object, and it thus makes the whole purpose of threadlocal moot. Use a global.

> If that's the case, and assuming I want to iterate over the dictionary
> without it changing under my nose while I'm in the loop, would it be
> better to encase the whole loop in lock-protected section or  would it
> be better to make a copy of the dictionary first and then iterate over
> that one? Given that in this particular thread I do not want to modify
> the dictionary, conceptually a copy would work. But would making
> thread-local copy be just as slow as making the whole loop thread
> safe?

As MRAB pointed out - it depends. My gut feeling on this is that the copy-approach is fastest. Or even faster, if you can cope with keys getting lost while processing them:


for key in self.myDictionary.keys():
    try:
       value = self.myDictionary[key]
    except KeyError:
       pass


Diez
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to