Thread safetyness in Python

jepler at unpythonic.net jepler at unpythonic.net
Wed Jul 3 18:24:09 EDT 2002


On Wed, Jul 03, 2002 at 12:15:02PM -0400, Tim Peters wrote:
> Another way to look at it is that
> 
>     list += iterable
> 
> is equivalent to
> 
>     list.extend(iterable)
> 
> except that under the covers the implementation makes the former act like
> 
>     list.extend(iterable)
>     list = list
> 
> The bytecode for the "list = list" part has no effect in the end, so doesn't
> matter.

However, you could notice something awry in the following case:
    Thread 1	    Thread 2
    _temp = l
    _temp.extend(iterable)
		    l = 37
    l = _temp

if the += was atomic, then the order would have to be

    Thread 1	    Thread 2
    _temp = l
    _temp.extend(iterable)
    l = _temp
		    l = 37
or
    Thread 1	    Thread 2
		    l = 37
    _temp = l
    _temp.extend(iterable)
    [exception raised, no 'extend' attribute]

But since the operation is not actually atomic, you can end up with 37 not
actually stored in 'l'.

Jeff





More information about the Python-list mailing list