22
22
for i in range(1, 6):
23
23
print(i)
24
24
25
- # Create a thread
26
- thread = threading.Thread(target=print_numbers)
25
+ # Create a thread
26
+ thread = threading.Thread(target=print_numbers)
27
27
28
- # Start the thread
29
- thread.start()
28
+ # Start the thread
29
+ thread.start()
30
30
31
- # Wait for the thread to complete
32
- thread.join()
31
+ # Wait for the thread to complete
32
+ thread.join()
33
33
34
34
- Synchronizing Threads
35
35
When multiple threads access shared resources, synchronization is necessary to avoid data corruption. The threading module provides
@@ -46,22 +46,22 @@ thread.join()
46
46
for i in range(1, 6):
47
47
print(i)
48
48
49
- # Create multiple threads
50
- threads = [ threading.Thread(target=print_numbers) for _ in range(3)]
49
+ # Create multiple threads
50
+ threads = [ threading.Thread(target=print_numbers) for _ in range(3)]
51
51
52
- # Start the threads
53
- for thread in threads:
54
- thread.start()
52
+ # Start the threads
53
+ for thread in threads:
54
+ thread.start()
55
55
56
- # Wait for all threads to complete
57
- for thread in threads:
58
- thread.join()
56
+ # Wait for all threads to complete
57
+ for thread in threads:
58
+ thread.join()
59
59
60
- - Thread Communication
61
- Threads can communicate using shared variables, but this requires careful synchronization. Another approach is to use thread-safe data
62
- structures like Queue from the queue module.
60
+ - Thread Communication
61
+ Threads can communicate using shared variables, but this requires careful synchronization. Another approach is to use thread-safe data
62
+ structures like Queue from the queue module.
63
63
64
- ** Example using Queue
64
+ ** Example using Queue
65
65
66
66
import threading
67
67
import queue
@@ -74,20 +74,20 @@ for thread in threads:
74
74
75
75
q = queue.Queue()
76
76
77
- # Add items to the queue
78
- for item in range(1, 11):
77
+ # Add items to the queue
78
+ for item in range(1, 11):
79
79
q.put(item)
80
80
81
- # Create and start worker threads
82
- threads = [ threading.Thread(target=worker, args=(q,)) for _ in range(3)]
81
+ # Create and start worker threads
82
+ threads = [ threading.Thread(target=worker, args=(q,)) for _ in range(3)]
83
83
84
- for thread in threads:
85
- thread.start()
84
+ for thread in threads:
85
+ thread.start()
86
86
87
- # Wait for all tasks to be processed
88
- q.join()
89
- Example: Multithreading in Python
90
- Let's create a more comprehensive example to demonstrate multithreading in a real-world scenario.
87
+ # Wait for all tasks to be processed
88
+ q.join()
89
+ Example: Multithreading in Python
90
+ Let's create a more comprehensive example to demonstrate multithreading in a real-world scenario.
91
91
92
92
- Example: Downloading Multiple URLs
93
93
0 commit comments