[New-bugs-announce] [issue12680] cPickle.loads is not thread safe due to non-thread-safe imports

Sagiv Malihi 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:

import time
class A(object):
    def __setstate__(self, state):
        self.x = x
time.sleep(1)
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
messages: 141548
nosy: Sagiv.Malihi
priority: normal
severity: normal
status: open
title: cPickle.loads is not thread safe due to non-thread-safe imports
type: crash
versions: Python 2.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue12680>
_______________________________________


More information about the New-bugs-announce mailing list