Skip to content

Commit b394f4b

Browse files
committed
Add introduction to docs for threading module
1 parent c9b399f commit b394f4b

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Doc/library/threading.rst

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,54 @@
88

99
--------------
1010

11+
Introduction
12+
------------
13+
14+
The :mod:`threading` module provides a way to run multiple threads (smaller
15+
units of a process) concurrently within a single process. It allows for the
16+
creation and management of threads, making it possible to execute tasks in
17+
parallel, sharing memory space. Threads are particularly useful when tasks are
18+
I/O-bound, such as reading from or writing to files, or making network requests,
19+
where much of the time is spent waiting for external resources.
20+
21+
Unlike the :mod:`multiprocessing` module, which uses separate processes to
22+
bypass the :term:`Global Interpreter Lock <global interpreter lock>`, the
23+
threading module operates within a single process, meaning that all threads
24+
share the same memory space. However, the GIL limits the performance gains of
25+
threading when it comes to CPU-bound tasks, as only one thread can execute
26+
Python bytecode at a time. Despite this, threading remains a useful tool for
27+
achieving concurrency in many scenarios.
28+
29+
A typical use case for :mod:`threading` includes managing a pool of worker
30+
threads that can process multiple tasks concurrently. This basic example of
31+
creating and starting threads using :class:`~threading.Thread`::
32+
33+
import threading
34+
import time
35+
36+
def crawl(link, delay=3):
37+
print(f"crawl started for {link}")
38+
time.sleep(delay)
39+
print(f"crawl ended for {link}")
40+
41+
links = [
42+
"https://example.com",
43+
"https://another-example.com",
44+
"https://yet-another-example.com"
45+
]
46+
47+
# Start threads for each link
48+
threads = []
49+
for link in links:
50+
# Using `args` to pass positional arguments and `kwargs` for keyword arguments
51+
t = threading.Thread(target=crawl, args=(link,), kwargs={"delay": 2})
52+
threads.append(t)
53+
t.start()
54+
55+
# Wait for all threads to finish
56+
for t in threads:
57+
t.join()
58+
1159
This module constructs higher-level threading interfaces on top of the lower
1260
level :mod:`_thread` module.
1361

0 commit comments

Comments
 (0)