Is defaultdict thread safe?

F

Frank Millman

Hi all

Is defaultdict thread safe?

Assume I have -

from collections import defaultdict
my_dict = defaultdict(list)

If two threads call "my_dict['abc'].append(...)" simultaneously, is it
guaranteed that my_dict['abc'] will end up containing two elements?

Thanks

Frank Millman
 
R

Raymond Hettinger

Hi all

Is defaultdict thread safe?

Sometimes. It depends on whether an operation has callbacks to pure
Python.

Assume I have -

    from collections import defaultdict
    my_dict = defaultdict(list)

If two threads call "my_dict['abc'].append(...)" simultaneously, is it
guaranteed that my_dict['abc'] will end up containing two elements?

Yes.

But, if the constructor is a user defined class, the pure python code
runs for the instantiation and all bets are off.

class A:
def __init__(self):
. . .
my_dict = defaultdict(A) # not thread-safe.


Raymond
 
F

Frank Millman

Is defaultdict thread safe?

Sometimes. It depends on whether an operation has callbacks to pure
Python.
Assume I have -
from collections import defaultdict
my_dict = defaultdict(list)
If two threads call "my_dict['abc'].append(...)" simultaneously, is it
guaranteed that my_dict['abc'] will end up containing two elements?

Yes.

But, if the constructor is a user defined class, the pure python code
runs for the instantiation and all bets are off.

class A:
def __init__(self):
. . .
my_dict = defaultdict(A) # not thread-safe.

Raymond

Many thanks

Frank
 
S

Stefan Behnel

Frank Millman, 25.01.2010 09:59:
Is defaultdict thread safe?

Assume I have -

from collections import defaultdict
my_dict = defaultdict(list)

If two threads call "my_dict['abc'].append(...)" simultaneously, is it
guaranteed that my_dict['abc'] will end up containing two elements?

Thread-safety is implementation specific. Other runtime environments than
CPython (e.g. Jython, IronPython, PyPy) may or may not provide any
guarantees on thread safety here.

Stefan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top