How to Start a Thread in Python
First of all, we will discuss the thread. So, what is a thread? Threading as the name suggests it’s happening of two or more things at the same time.
In Python, a thread refers to an entity within a process that can be scheduled for execution. Threads are generally used in multi-threading for the purpose of multi-tasking.
A point to remember about threading is that a thread can be scheduled during program execution. Thread is also independent of the main program and can be executed individually too.
Threading in Python enables it to execute other programs while being on hold. Below is the Python program on how to use threading in Python by using the threading library.
Using class to create Python Thread
class thread_demo(threading.Thread): def __init__(self, name, id): threading.Thread.__init__(self) self.name = name self.id = id def run(self): print(str(self.name) +" "+ str(self.id)); t1 = thread_demo("Gaurav", 100) t2 = thread_demo("CodeSpeedy", 200); t1.start() t2.start() print("Exit")
Gaurav 100 CodeSpeedy 200 Exit
Let’s understand the above Python code:
We created a thread class and then we used __init__ function to read the parameters. Then for deciding the nature of the thread we used the run method. The function “t1.start” marks the beginning of the thread.
Using Function to create Thread
from threading import Thread from time import sleep # creating thread def thread(args): for i in range(args): print("running") # wait 0.5 sec in each thread sleep(0.5) if __name__ == "__main__": t = Thread(target = thread, args= (5, )) t.start() t.join() print("Thread Terminated")
running running running running running Thread Terminated
In the above code, we defined a function to create a thread. We also used the sleep() function to make each thread wait for 0.5 sec before executing and then we used the “t.start()” function to start the thread.
We can also see this method in the other Python code written below:
import threading import time print("Values from 10 to 20: ") def thread(): for i in range(10, 21): time.sleep(1) print(i) threading.Thread(target=thread).start()
Values from 10 to 20: 10 11 12 13 14 15 16 17 18 19 20
Here in the above Python program first we are importing the thread library using import then we are using the print function to print the text (Value from 1 to 10: ) on the screen. After that, we are creating a function “thread” using the def keyword.
After creating the function, we are using for loop to read all the values and use time. sleep function. After that, we are creating a thread by using threading. (“The name of the function created” ) here we have created “thread” as the function.
You can also refer to this link Multi-Threading and multitasking in Python to study further on Thread and its functions.