Author name: Minh Nguyen
Thread in python is a flow of execution, like a separate order of instructions. That means your program can run many functions at once.
import threading
import time
def eat_dinner():
time.sleep(5)
print('You eat dinner')
def study():
time.sleep(5)
print('You finish studying')
def go_to_bed():
time.sleep(3)
print('You sleep')
eat_dinner()
study()
go_to_bed()
For this code, it takes 13 seconds to run this code. But if you use “threading” it will be different. You can see below👇
import threading
import time
def eat_dinner():
time.sleep(5)
print('You eat dinner')
def study():
time.sleep(5)
print('You finish studying')
def go_to_bed():
time.sleep(3)
print('You sleep')
x = threading.Thread(target=eat_dinner, arg=())
x.start()
y = threading.Thread(target=study, arg=())
y.start()
z = threading.Thread(target=go_to_bed, arg=())
z.start()
Target is your function and arg is the argument if you need it. Because “threading” runs 3 functions at once, it just needs 1 sec to run this code. We need thread python because it is useful in situations where concurrent execution is required. You can go to realpython or Bro code to see more information.
No Responses