February 17, 2021

How to Create Thread in Python

In Python, threading module has a Thread class which is used for creating thread. There are two ways to create a new Thread in Python.

  1. By creating Thread instance and passing the function that has to be executed as one of the argument to the constructor of the Thread.
  2. By creating a class that extends Thread class and overrides run method.

1. Python thread creation using threading.Thread() constructor

In Python you don’t have to always create classes. You can just create a Python file with functions for some scripting purposes. In such scenario if you want to take advantage of multi-threading, threading.Thread() is the way to go (Though you can use it with classes too). You need to pass the function that has to be executed as one of the argument to the constructor of the Thread.

Full constructor call with all the arguments is as given below-

threading.Thread(group=None, target=None, name=None, 
           args=(), kwargs={}, *, daemon=None)

This constructor should always be called with keyword arguments. Arguments are:

  • group should be None. This argument is reserved for future extension
  • target is the function that has to be invoked. Defaults to None, meaning nothing is called.
  • name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a decimal number.
  • args is the argument passed to the target function. It is passed as a tuple. Defaults to ().
  • kwargs is a dictionary of keyword arguments passed to the target function. Defaults to {}.
  • daemon if set to True runs the thread as a daemon thread. If None (the default), the daemonic property is inherited from the current thread.

Let us write a Python program to understand how to create thread using threading.Thread(). In the example there are two functions and three threads are spawned.

import threading

def print_thread_info():
  print('Thread Name: ' + threading.current_thread().name)

def add(a, b):
  result = a + b
  print('Thread Name: ' + threading.current_thread().name + ' Sum is', result)


if __name__ == "__main__":
  # Creating threads
  t1 = threading.Thread(target=print_thread_info)
  t2 = threading.Thread(target=add, name='MyThread-1', args=(4, 5))
  t3 = threading.Thread(target=add, name='MyThread-2', args=(19, 28))
  # starting threads
  t1.start()
  t2.start()
  t3.start()
Output
Thread Name: Thread-1
Thread Name: MyThread-1 Sum is  9
Thread Name: MyThread-2 Sum is  47

In the program points to note are-

  • Since you are using multi-threading so threading module has to be imported.
    import threading
    
  • In the first instance target function is print_thread_info no other argument is passed so defaults will be used for other arguments.
  • For the other two Thread instances target function is sum, argument to the function are passed using args and thread name is also passed.
  • To start thread’s activity start() method has to be invoked on a thread. Once the thread is started it arranges for the object’s run() method to be invoked in a separate thread of control.
  • run() method invokes the callable object passed to the object’s constructor as the target argument.

2. Python thread creation using threading.Thread() constructor where methods of a class is invoked

As mentioned above you can also use threading.Thread() constructor where target is a method of a class. In that case you will have to create object of the class and pass object_name.method_name as target. In the example there is a class ThreadDemo with two methods. Then an object obj of the class is created so the target can be specified as obj.print_thread_info or obj.sum

import threading

class ThreadDemo:

    def print_thread_info(self):
        print('Thread Name: ' + threading.current_thread().name)

    def add(self, a, b):
        result = a + b
        print('Thread Name: ' + threading.current_thread().name + ' Sum is', result)


obj = ThreadDemo()
t1 = threading.Thread(target=obj.print_thread_info)
t2 = threading.Thread(target=obj.add, name='MyThread-1', args=(4, 5))
t3 = threading.Thread(target=obj.add, name='MyThread-2', args=(19, 28))
# starting threads
t1.start()
t2.start()
t3.start()
Output
Thread Name: Thread-1
Thread Name: MyThread-1 Sum is 9
Thread Name: MyThread-2 Sum is 47

3. Python Thread creation using class that extends Thread class

You can create a class extending Thread class which makes your class also of type Thread. In your subclass override the run() method of the Thread class and provide the functionality that you want to be executed by the threads. When you will create instance of your class (which is also of type Thread because of inheritance) and call start() method, threads will execute the overridden run() method of this class.

import threading

# inherit from Thread class
class MyThread(threading.Thread):
    def __init__(self, msg):
        # Calling Thread class constructor
        super().__init__()
        self.msg = msg

    def run(self):
        print('Message is- ' + self.msg)

# Creating thread
t1 = MyThread('Executing Thread')
t2 = MyThread('Executing Another Thread')
# starting thread
t1.start()
t2.start()
Output
Message is- Executing Thread
Message is- Executing Another Thread

In the program points to note are-

  • Thread class is extended by the class so MyThread class inherits class members of Thread class.
  • run() method is overridden and that is where you write the logic that has to be executed by a thread.
  • In the constructor (__init__()) super() function is used to call parent class constructor.
  • When you create instance of your MyThread class those objects are also of type Thread as Thread class is the parent class.
  • To start thread’s activity start() method has to be invoked on a thread which arranges for the object’s run() method to be invoked in a separate thread of control. The start() method must be called at most once per thread object.

That's all for the topic How to Create Thread in Python. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment