Re: Is defaultdict thread safe?

2010-01-25 Thread 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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is defaultdict thread safe?

2010-01-25 Thread Frank Millman

On Jan 25, 11:26 am, Raymond Hettinger  wrote:

On Jan 25, 12:59 am, "Frank Millman"  wrote:

> 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


Many thanks

Frank


--
http://mail.python.org/mailman/listinfo/python-list


Re: Is defaultdict thread safe?

2010-01-25 Thread Raymond Hettinger
On Jan 25, 12:59 am, "Frank Millman"  wrote:
> 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

-- 
http://mail.python.org/mailman/listinfo/python-list