Thread Object
In the previous blog we used an object of the class Thread to create and start a thread, as shown below:
variable = threading.Thread(target=function_name, args=[1])
Let us take a closer at the Thread class. The most frequently used aspect of the threading module is the Thread class. The Thread class allows us to create and run threads, and it also gives us all that we need to manage it as well.
NOTE: When we say Thread Object it is another way of saying an object of the class Thread
There are two ways in which we can tell the Thread object, what it should do:
- Create an object of the class Thread and then specify the function we want to use with the “target” argument.
- Create a subclass of the Thread class and then overriding the run() function.
The run() function represents the activity (code to execute) of the thread. Since we have seen the first method in the previous blog, let’s have a glance at creating a custom thread subclass from the Thread class.
import threading class custom_thread(threading.Thread): def __init__(self): # after self we can add custom parameters threading.Thread.__init__(self) # your code # Overriding the run() function from the parent class def run(self): print("Do something") object_of_custom_thread = custom_thread() object_of_custom_thread.start()
If we run this we get:
In both the ways, the run() method is called or invoked. While we explicitly call the run() function when we create a subclass, an object of Thread will have the run() function called for us when we start the thread [thread_object.start()]. However, there is a crucial difference, in the first approach the code is executed inside the new thread that we created whereas in the second approach the code is executed inside the current thread.
Inner-working of a Thread
When we create an object of the class Thread, we must call its start() function to initiate the activity of that class. Once a thread’s activity has started it is considered to be alive, and only stops being alive when the run() function ends either normally or when the program faces an error that is not handled.
The isAlive() function checks whether the thread is still alive or not. As we saw before calling join on a thread, we create halts another thread’s (the main thread) execution till the threads we create have completed execution.
A thread has a name and we can set it when we create an object of the Thread class. We can also use the functions setname() and getname() to set and retrieve the name of a thread respectively.
We can also have a thread flagged as a Daemon Thread. A Daemon Thread is a thread that will always run in the background to provide support for main and non-daemon threads. However, they do not halt the execution of the main thread but carry on in the background. If a thread is Daemon, it will automatically be closed when the main thread has stopped. Using the functions setDaemon() and isDaemon() we can set a thread as Daemon and check the thread’s flag respectively.
The syntax of the Thread class is:
- Thread(group=None, target=None, name=None, args=(), kwargs={})
- group – By default, it is None, and must be None as it is reserved for future extension when the “ThreadGroup” class is implemented.
- target – It is the function to be called by the run() method and by default is None.
- name – Specify a name for the thread. By default, it is “Thread-N” where N is a small decimal number.
Consider an example of specifying the name of the thread:
import threading, time def test_function(): print("Going to sleep now:") time.sleep(1) print(f"The currently active thread is: {threading.current_thread()}") print("Finished sleeping") time_1 = threading.Thread(target=test_function, name="Custom Name") time_2 = threading.Thread(target=test_function) time_1.start() time_2.start() time_1.join() time_2.join() print(f"The currently active thread is: {threading.current_thread()}") print("Script has ended"
One of our threads has a non-default name “Custom Name”.
- args – Specify the arguments we want our “target” function to use. By default it is empty.
- kwargs – A dictionary of keyword arguments for the target to use. By default it is empty.
What have we learned?
- What are the two different ways to use the Thread class?
- What is the crucial difference between these two ways?
- What is the activity of a thread?
- Which function handles the activity of a thread?
- When does a thread become alive and when does it stop?
- What is a Daemon thread?
- What is the syntax for creating a Thread object?