[issue12680] cPickle.loads is not thread safe due to non-thread-safe imports
report at bugs.python.org
Tue Aug 2 10:16:09 CEST 2011
New submission from Sagiv Malihi <sagivmalihi at gmail.com>:
When trying to cPickle.loads() from several threads at once, there is a race condition when threads try to import modules.
An example will explain it best:
suppose I have module foo.py which takes some time to load:
def __setstate__(self, state):
self.x = x
x = 5
and a pickled version of an A() object stored in 'A.pkl'.
the following code, when run for the first time, will raise a NameError about 'x':
>>> p = open('A.pkl','rb').read()
>>> [thread.start_new(cPickle.loads, (p,)) for x in xrange(2)]
Unhandled exception in thread started by <built-in function loads>
Traceback (most recent call last):
File "foo.py", line 7, in __setstate__
self.x = x
NameError: global name 'x' is not defined
since the module is now loaded, subsequent calls to cPickle.loads will work as expected.
This was tested on 2.5.2, 2.7.1, and 3.2 on Ubuntu and on Windows 7.
please note that this bug was discovered when unpickling the standard 'decimal.Decimal' class (decimal.py is quite long and takes some time to import), and this is not some corner case.
components: Extension Modules
title: cPickle.loads is not thread safe due to non-thread-safe imports
versions: Python 2.7
Python tracker <report at bugs.python.org>
More information about the Python-bugs-list