Sometimes, we want to create threads in Python.
In this article, we’ll look at how to create threads in Python.
How to create threads in Python?
To create threads in Python, we can use the Thread class.
For instance, we write
from threading import Thread
from time import sleep
def threaded_function(arg):
for i in range(arg):
print("running")
sleep(1)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = (10, ))
thread.start()
thread.join()
to create a Thread object that runs the threaded_function function with 10 as its argument.
Then we call start to start the thread.
And we call join to block the calling thread until the thread that called join is terminated.
Conclusion
To create threads in Python, we can use the Thread class.