Repository navigation
Expand file tree
/
Copy path6_multi_threading.py
More file actions
82 lines (55 loc) · 2.17 KB
/
Copy path6_multi_threading.py
File metadata and controls
82 lines (55 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#* Multi-threading in Python
# Multi-threading allows concurrent execution of code, which can improve performance for I/O-bound tasks.
# However, due to the Global Interpreter Lock (GIL), CPU-bound tasks may not see significant performance gains.
#Use case:
# Multi-threading is useful when you have tasks that are I/O-bound, such as reading/writing files, making network requests, or interacting with databases.
# It allows these tasks to run concurrently, improving overall performance.
#Example without using multi-threading
import time # Added import for time module, required for sleep function in multi-threading examples
def print_numbers():
for i in range(5):
print(i)
time.sleep(1)
def print_letters():
for letter in 'abcde':
print(letter)
time.sleep(1)
print_numbers()
print_letters()
# # Example of multi-threading in Python using the threading module:
import threading
import time
def print_numbers():
for i in range(5):
print(i)
time.sleep(1)
def print_letters():
for letter in 'abcde':
print(letter)
time.sleep(1)
# Creating threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Starting threads
thread1.start()
thread2.start()
# Waiting for threads to complete
thread1.join()
thread2.join()
print("Both threads have completed.")
# -----------------------------------------------------------------------------------------------------------------------
# Example of multi-threading using a threadpool Executor from the concurrent.futures module:
import concurrent.futures
def print_numbers():
for i in range(5):
print(i)
time.sleep(1)
def print_letters():
for letter in 'abcde':
print(letter)
time.sleep(1)
# Using ThreadPoolExecutor to run the functions concurrently with a maximum of 2 worker threads(max_workers ideally should match the number of concurrent tasks but maximum is system dependent)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(print_numbers)
executor.submit(print_letters)
print("Both threads have completed using ThreadPoolExecutor.")