jeff at ccvcorp.com
Wed Oct 13 22:07:24 CEST 2004
Diez B. Roggisch wrote:
>But so far in my expirience, explicit serialization of access to certain
>data structures was only necessary when more complicated structural
>modifications where under way - but the usual suspects, as appending to
>lists, insertion of values in dicts and the like never needed this. And
>that I wanted to point out.
... provided, of course, that no thread expects to maintain internal
consistency. For example, a thread doing something like:
assert(foo == foo_list[-1])
The assertion here is *not* guaranteed to be true, and if one is
modifying and then reading a mutable object, it can be somewhat tricky
to ensure that no such assumptions creep into code.
if foo_list[-1] is not None:
foo = foo_list.pop()
Here, foo may indeed be None, because another thread may have appended
to the list in between the test and the call to pop() -- but this is
getting into the "more complicated structural modifications" that you
A slightly trickier example, though:
foo_list[-1] == foo_list[-1]
I believe that this can't be guaranteed to always evaluate to True in a
(non-locking) multithreaded case, because foo_list can be modified in
between the two lookups.
Thus, while it's pretty safe to assume that accessing shared objects
won't, in and of itself, cause an exception, the case about "mangled
data" is hazier and depends on how exactly you mean "mangled".
I expect that most of us know this and would never assume otherwise, I
just wanted to make that explicit for the benefit of the O.P. and others
who're unfamiliar with threading, as it seems to me that this point
might've gotten a bit confused for those who didn't already understand
it well. :)
More information about the Python-list