Thread safetyness in Python

Oren Tirosh oren-py-l at hishome.net
Wed Jul 3 14:18:14 EDT 2002


On Wed, Jul 03, 2002 at 10:34:28AM -0500, Skip Montanaro wrote:
> 
>     Oren> So a+=1 isn't atomic, but l+=[1] is. Interesting.
> 
> How so?
> 
>     >>> def f(l):
>     ...   l += [1]
>     ... 
>     >>> dis.dis(f)
>               0 LOAD_FAST                0 (l)
>               3 LOAD_CONST               1 (1)
>               6 BUILD_LIST               1
>               9 INPLACE_ADD         
>              10 STORE_FAST               0 (l)
>              13 LOAD_CONST               0 (None)
>              16 RETURN_VALUE        
> 
> Looks to me like there's the opportunity for another thread to sneak in
> there and modify l between the LOAD_FAST and STORE_FAST instructions...

That is also true of l.append(1) - if another thread modifies the binding
of the name l it doesn't matter so much if the append operation on the 
object it previously pointed to was atomic or not.

Assuming the two threads both use l+=[x] or otherwise modify the object but
avoid rebinding the reference they should be ok.

	Oren






More information about the Python-list mailing list