Custom Thread
creating custom thread
- We can inherit
Threadclass and create our own implementation ofrunmethod. - We only need to implement
__init__andrunmethod. - Then, we can use
start,joinand other methods as we did withthreadclass.
from threading import Thread
class MyThread(Thread):
def __init__(self, num):
self.num = num
super().__init__() # calling the parent class constructor (required)
def run(self):
for i in range(10):
print(f"I'm thread: {self.num} => {i}")
if __name__ == "__main__":
my_t = []
for i in range(5):
curr_t = MyThread(i+1)
my_t.append(curr_t)
print("=== start all the threads ===")
for t in my_t:
t.start()
for t in my_t:
t.join()
print("=== all threads finished ===")
Make custom daemon thread
- to make the thread
a daemon thread, we can setdaemon=Truein the constructor.
Methods of Thread
start: This method starts the thread.join(timeout=None): This method waits infinitely for the thread to finish.-
join(timeout): This method waits for the thread to finish for the specified time.join()method always returnNone. So to check if thejoin() methodcompleted bcoz task is over, or due to timeout, we can useis_alive()method. -
If
is_alive()returnsTrue, then the thread is still running, and timeout has occurred (ifjoin(timeout)is completed).