Skip to content
Merged
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions Doc/library/threading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,64 @@ level :mod:`_thread` module.

.. include:: ../includes/wasm-notavail.rst

Introduction
------------

The :mod:`threading` module provides a way to run multiple threads (smaller
units of a process) concurrently within a single process. It allows for the
creation and management of threads, making it possible to execute tasks in
parallel, sharing memory space. Threads are particularly useful when tasks are
I/O-bound, such as file operations or making network requests,
where much of the time is spent waiting for external resources.

A typical use case for :mod:`threading` includes managing a pool of worker
threads that can process multiple tasks concurrently. This basic example of
creating and starting threads using :class:`~threading.Thread`::

import threading
import time

def crawl(link, delay=3):
print(f"crawl started for {link}")
time.sleep(delay) # Blocking I/O, simulating a network request
print(f"crawl ended for {link}")

links = [
"https://python.org",
"https://docs.python.org",
"https://peps.python.org"
]

# Start threads for each link
threads = []
for link in links:
# Using `args` to pass positional arguments and `kwargs` for keyword arguments
t = threading.Thread(target=crawl, args=(link,), kwargs={"delay": 2})
threads.append(t)

# Start each thread
for t in threads:
t.start()

# Wait for all threads to finish
for t in threads:
t.join()

GIL and Performance Considerations
----------------------------------

Unlike the :mod:`multiprocessing` module, which uses separate processes to
bypass the :term:`Global Interpreter Lock <global interpreter lock>`, the
threading module operates within a single process, meaning that all threads
share the same memory space. However, the :term:`GIL` limits the performance
gains of threading when it comes to CPU-bound tasks, as only one thread can
execute Python bytecode at a time. Despite this, threads remain a useful tool
for achieving concurrency in many scenarios.

As of Python 3.13, experimental :term:`free-threaded <free threading>` builds
can disable the :term:`GIL`, enabling true parallel execution of threads, but
this feature is not available by default. (See :pep:`703`.)

This module defines the following functions:


Expand Down
Loading