Skip to content

Commit 1858ef5

Browse files
committed
gh-142518: Document thread-safety guarantees of list operations
1 parent 8392095 commit 1858ef5

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Doc/library/stdtypes.rst

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1369,6 +1369,48 @@ Lists are mutable sequences, typically used to store collections of
13691369
homogeneous items (where the precise degree of similarity will vary by
13701370
application).
13711371

1372+
.. note::
1373+
1374+
Individual operations on list such as :meth:`~list.append`, :meth:`~list.pop`,
1375+
``lst[i] = x``, and ``x = lst[i]`` are atomic and will not corrupt the
1376+
list or crash when called concurrently from multiple threads:
1377+
1378+
.. code-block::
1379+
:class: good
1380+
1381+
# These operations are safe to call concurrently from multiple threads
1382+
lst.append(item) # atomically appends item
1383+
lst.pop() # atomically removes and returns last item
1384+
lst[i] = value # atomically replaces item at index i
1385+
item = lst[i] # atomically retrieves item at index i
1386+
1387+
One exception to this rule is :meth:`~list.extend`. Its atomicity
1388+
guarantees depend on the iterable being passed. When the iterable is
1389+
a :class:`list`, a :class:`tuple`, a :class:`set`, a :class:`frozenset`,
1390+
a :class:`dict` or a :ref:`dictionary view object <dict-views>`, the
1391+
operation is atomic. Otherwise, an iterator is created which can be
1392+
concurrently modified by another thread.
1393+
1394+
Operations that involve multiple accesses, as well as iteration, are not
1395+
atomic. For example, the following patterns are not thread-safe:
1396+
1397+
.. code-block::
1398+
:class: bad
1399+
1400+
# NOT atomic: read-modify-write
1401+
lst[i] = lst[i] + 1
1402+
1403+
# NOT atomic: check-then-act
1404+
if lst:
1405+
item = lst.pop()
1406+
1407+
# NOT thread-safe: iteration while modifying
1408+
for item in lst:
1409+
process(item) # another thread may modify lst
1410+
1411+
Consider external synchronization when sharing :class:`list` instances
1412+
across threads. See :ref:`freethreading-python-howto` for more information.
1413+
13721414
.. class:: list(iterable=(), /)
13731415

13741416
Lists may be constructed in several ways:

0 commit comments

Comments
 (0)