-
Notifications
You must be signed in to change notification settings - Fork 1
/
1_basic_thread.py
41 lines (31 loc) · 1.44 KB
/
1_basic_thread.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
# I/O-bound processes (user input)
from threading import Thread, current_thread, main_thread
class InputReader(Thread):
'''
To construct a thread, we must extend the Thread class and implement the run method.
Any code executed by the run method happens in a separate thread.
'''
def run(self):
self.line_of_text = input()
print(f'{thread.name}, TID={thread.native_id}, PID={main_thread().native_id}')
if __name__ == "__main__":
print(f'{current_thread().name} - PID={current_thread().native_id}') # same as os.getpid()
# (2) input
print("Enter some text and press enter: ")
thread = InputReader()
thread.start()
# (1) main
number = result = 1
while thread.is_alive():
result = number * number
number += 1
print(f"calculated squares up to {number} * {number} = {result} while you typed '{thread.line_of_text}'")
'''
These threads allows to (1) calculate squares while (2) getting input from keyboard.
Thread (2) doesn't start running until we call the start() method on the object.
It starts and immediately pauses to wait for input from the keyboard.
In the meantime, the original thread continues executing from the point start() was called.
It starts calculating squares inside a while loop. The condition in the while loop checks
whether the InputReader thread has exited its run method yet; once it does, it outputs
some summary information to the screen.
'''