Why doesn't this fail?
Alan Kennedy
alanmk at hotmail.com
Wed Oct 9 10:10:54 EDT 2002
Hi all,
I'm writing some code that uses threads to iterate over a
read-only object that is shared between all threads.
The object contains lists of items. The object also has a
method, which iterates over the lists, using a local variable
(not an object data member).
I would expect that the local
variable would be shared between threads. So, without mutual
exclusion, I expect that using that local variable should cause
errors in a multi-threaded situation.
But it doesn't. Here is some sample code that illustrates what
I mean.
==========
import threading
import time
limit = 100000
class datastruct:
def __init__(self):
self.ls = []
for ix in xrange(limit):
self.ls.append(ix)
def visit(self, markerdict):
for x in self.ls:
del markerdict[x]
sharedstruct = datastruct()
class thr(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self.markerdict = {}
for ix in xrange(limit):
self.markerdict[ix] = 1
sharedstruct.visit(self.markerdict)
print "Thread %s missed %s" % (self.getName(),
self.markerdict.keys())
if __name__ == "__main__":
for x in range(10):
t = thr()
t.start()
=======
Each thread keeps a thread-private list of values that have been
processed, so that it can know at the end what it missed out on.
When I run this code, each of the threads visits every value, with no
problem! Why?
When I change the datastruct.visit method to use an object data member
as the loop variable, like so
def visit(self, markerdict):
for self.x in self.ls:
del markerdict[self.x]
lots of KeyErrors are generated, as I would expect, because the value
"self.x" is definitely shared between all threads.
So, despite my expectations, it appears that local variables are indeed
per-thread?
I wanted to check, before declaring my code thread-safe. I feel uneasy
"just hoping".
Regards,
alan kennedy
----------------------------------------------
check http headers here: xhaus.com/headers
email alan: xhaus.com/mailto/alan
More information about the Python-list
mailing list