Skip to content

Commit fd400f0

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

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Doc/library/stdtypes.rst

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

13741417
Lists may be constructed in several ways:

0 commit comments

Comments
 (0)