Is extending a Python list (e.g. l += [1]) guaranteed to be thread-safe?

后端 未结 2 1589
借酒劲吻你
借酒劲吻你 2021-02-01 05:37

If I have an integer i, it is not safe to do i += 1 on multiple threads:

>>> i = 0
>>> def increment_i():
...     glo         


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 05:47

    From http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm :

    Operations that replace other objects may invoke those other objects’ __del__ method when their reference count reaches zero, and that can affect things. This is especially true for the mass updates to dictionaries and lists.

    The following operations are all atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y are objects, i, j are ints):

    L.append(x)
    L1.extend(L2)
    x = L[i]
    x = L.pop()
    L1[i:j] = L2
    L.sort()
    x = y
    x.field = y
    D[x] = y
    D1.update(D2)
    D.keys()
    

    These aren’t:

    i = i+1
    L.append(L[-1])
    L[i] = L[j]
    D[x] = D[x] + 1
    

    Above is purely CPython specific and can vary across different Python implemenation such as PyPy.

    By the way there is an open issue for documenting atomic Python operations - https://bugs.python.org/issue15339

提交回复
热议问题