Skip to content

Commit 8a250ae

Browse files
committed
Merged revisions 64601 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/trunk ........ r64601 | amaury.forgeotdarc | 2008-06-30 17:42:40 -0500 (Mon, 30 Jun 2008) | 11 lines #Issue3088 in-progress: Race condition with instances of classes derived from threading.local: When a thread touches such an object for the first time, a new thread-local __dict__ is created, and the __init__ method is run. But a thread switch can occur here; if the other thread touches the same object, it installs another __dict__; when the first thread resumes, it updates the dictionary of the second... This is the deep cause of the failures in test_multiprocessing involving "managers" objects. Also a 2.5 backport candidate. ........
1 parent ec19d95 commit 8a250ae

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

‎Lib/test/test_threading_local.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,32 @@ def _local_refs(self, n):
4242
deadlist = [weak for weak in weaklist if weak() is None]
4343
self.assert_(len(deadlist) in (n-1, n), (n, len(deadlist)))
4444

45+
def test_derived(self):
46+
# Issue 3088: if there is a threads switch inside the __init__
47+
# of a threading.local derived class, the per-thread dictionary
48+
# is created but not correctly set on the object.
49+
# The first member set may be bogus.
50+
import time
51+
class Local(threading.local):
52+
def __init__(self):
53+
time.sleep(0.01)
54+
local = Local()
55+
56+
def f(i):
57+
local.x = i
58+
# Simply check that the variable is correctly set
59+
self.assertEqual(local.x, i)
60+
61+
threads= []
62+
for i in range(10):
63+
t = threading.Thread(target=f, args=(i,))
64+
t.start()
65+
threads.append(t)
66+
67+
for t in threads:
68+
t.join()
69+
70+
4571
def test_main():
4672
suite = unittest.TestSuite()
4773
suite.addTest(DocTestSuite('_threading_local'))

‎Modules/_threadmodule.c‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,10 @@ _ldict(localobject *self)
293293
}
294294

295295
}
296-
else if (self->dict != ldict) {
296+
297+
/* The call to tp_init above may have caused another thread to run.
298+
Install our ldict again. */
299+
if (self->dict != ldict) {
297300
Py_CLEAR(self->dict);
298301
Py_INCREF(ldict);
299302
self->dict = ldict;

0 commit comments

Comments
 (0)