|
8 | 8 |
|
9 | 9 | -------------- |
10 | 10 |
|
| 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 | + |
11 | 59 | This module constructs higher-level threading interfaces on top of the lower |
12 | 60 | level :mod:`_thread` module. |
13 | 61 |
|
|
0 commit comments