You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/python/concepts/threading/threading.md
+55-4Lines changed: 55 additions & 4 deletions
Original file line number
Diff line number
Diff line change
@@ -7,6 +7,7 @@ Subjects:
7
7
Tags:
8
8
- 'Async Await'
9
9
- 'Functions'
10
+
- 'Threads'
10
11
CatalogContent:
11
12
- 'learn-python-3'
12
13
- 'paths/computer-science'
@@ -26,14 +27,14 @@ import threading
26
27
27
28
The `threading` module must first be imported before thread constants can be created and their methods can be used.
28
29
29
-
## Example
30
+
## Example - How to Create and Run Threads in Python
30
31
31
32
The following example features five threads that are created, started, and end at different points before the program finishes:
32
33
33
34
```py
34
35
import threading, time, random
35
36
36
-
#simulates waiting time (e.g., an API call/response)
37
+
#Simulates waiting time (e.g., an API call/response)
37
38
defslow_function(thread_index):
38
39
time.sleep(random.randint(1, 10))
39
40
print("Thread {} done!".format(thread_index))
@@ -46,7 +47,7 @@ def run_threads():
46
47
threads.append(individual_thread)
47
48
individual_thread.start()
48
49
49
-
#at this point threads are running independently from the main flow of application and each other
50
+
#At this point, threads are running independently from the main flow of application and each other
50
51
print("Main flow of application")
51
52
52
53
# This ensures that all threads finish before the main flow of application continues
@@ -58,7 +59,7 @@ def run_threads():
58
59
run_threads()
59
60
```
60
61
61
-
This results in output like the following:
62
+
The output for the example will be:
62
63
63
64
```shell
64
65
Main flow of application
@@ -69,3 +70,53 @@ Thread 2 done!
69
70
Thread 0 done!
70
71
All threads are done
71
72
```
73
+
74
+
## Advantages and Use Cases of Python Threading
75
+
76
+
Python threading offers several advantages and is particularly useful in specific scenarios where concurrent execution can improve performance:
77
+
78
+
1.**Improved Responsiveness**: In GUI applications, threading keeps the interface responsive while performing background tasks.
79
+
80
+
2.**I/O-Bound Operations**: Threading is ideal for tasks that spend time waiting for external operations like file I/O, network requests, or database queries.
81
+
82
+
3.**Simplified Design**: When handling multiple simultaneous operations, threading can make program design clearer and more modular.
83
+
84
+
4.**Resource Efficiency**: Threads share memory and resources, making them more lightweight than separate processes.
85
+
86
+
5.**Concurrent Processing**: For operations that can run independently, threading allows concurrent execution, improving overall throughput.
87
+
88
+
Common use cases for threading include:
89
+
90
+
- Web scrapers and crawlers
91
+
- Server applications handling multiple client connections
92
+
- Background tasks in GUI applications
93
+
- File and network I/O operations
94
+
- Monitoring systems that check multiple services
95
+
96
+
## Frequently Asked Questions
97
+
98
+
### 1. Is asyncio better than threading?
99
+
100
+
Neither is universally better. **Asyncio** uses coroutines for cooperative multitasking within a single thread, making it efficient for many concurrent I/O operations. **Threading** provides actual concurrent execution but with overhead from thread switching. Choose asyncio for high-concurrency I/O tasks and threading for simpler implementation of blocking operations.
101
+
102
+
### 2. Is Python single-threaded or multithreaded?
103
+
104
+
Python supports **multithreading**, but the Global Interpreter Lock (GIL) in CPython allows only a single thread to execute Python bytecode at any moment. This means Python can run multiple threads simultaneously for I/O operations, but CPU-bound Python threads won't get true parallel execution in the standard implementation.
105
+
106
+
### 3. How many Python threads can I run?
107
+
108
+
The practical limit depends on:
109
+
110
+
- Available system memory
111
+
- CPU resources
112
+
- Nature of the workload (I/O vs CPU bound)
113
+
114
+
For I/O-bound applications, 10-100 threads is typically effective. Beyond that, context switching overhead often outweighs the benefits, and alternatives like asyncio may be more appropriate.
115
+
116
+
### 4. What is the difference between a thread and a process?
117
+
118
+
-**Memory**: Threads share memory; processes have separate memory spaces.
119
+
-**Resources**: Threads are lightweight; processes have higher overhead.
120
+
-**Communication**: Threads use shared memory; processes require IPC.
121
+
-**Isolation**: Thread crashes can affect other threads; processes are isolated.
122
+
-**Parallelism**: In Python, the GIL limits thread parallelism for CPU tasks; processes can run truly in parallel.
0 commit comments