-
Notifications
You must be signed in to change notification settings - Fork 11
/
multithreading.py
49 lines (40 loc) · 1.01 KB
/
multithreading.py
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
import threading
import time
from concurrent.futures import ThreadPoolExecutor
# Indicates some task being done
def func(seconds):
print(f"Sleeping for {seconds} seconds")
time.sleep(seconds)
return seconds
def main():
time1 = time.perf_counter()
# Normal Code
# func(4)
# func(2)
# func(1)
# Same code using Threads
t1 = threading.Thread(target=func, args=[4])
t2 = threading.Thread(target=func, args=[2])
t3 = threading.Thread(target=func, args=[1])
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
# Calculating Time
time2 = time.perf_counter()
print(time2 - time1)
def poolingDemo():
with ThreadPoolExecutor() as executor:
# future1 = executor.submit(func, 3)
# future2 = executor.submit(func, 2)
# future3 = executor.submit(func, 4)
# print(future1.result())
# print(future2.result())
# print(future3.result())
l = [3, 5, 1, 2]
results = executor.map(func, l)
for result in results:
print(result)
poolingDemo()