/, Python, Tech/Defining a Thread in Python

Defining a Thread in Python

The Python Threading Module

  • Python manages a thread via the threading package
  • It provides some very interesting features that make the threading-based approach easier
  • The threading module provides several synchronization mechanisms that are very simple to implement

Major Components of Threading Module

  • thread object
  • lock object
  • RLock object
  • semaphore object
  • condition object
  • event object

Defining a Thread

  • The simplest way to use a thread is to instantiate it with a target function and then call the start() method
  • The python module threading has the Thread() method

Syntax to Define a Thread

class threading.Thread(group=None,
target=None,
name=None,
args=(),
kwargs={})
  • target is the function to be executed when we start the thread activity
  • name is name of the thread. By default a unique thread name as threadN is assigned to it.
  • args is the tuple of arguments that is to be passed to the target function
  • kwargs is the dictionary of keyword arguments that are to be used by target function
  • It’s useful to pass arguments that tell a thread what work to do.

Sample Code

import threading


def func(i):
    print("Function called by thread {} \n".format(i))
    return


threads = []

for i in range(5):
    t = threading.Thread\
        (target=func, args=(i,))
    threads.append(t)
    t.start()
    t.join()
  • thread doesn’t starts running until start() method is called.
  • join()  makes the calling thread wait until the thread has finished the execution
  • NOTE: the output order cannot be predetermined as multiple thread might print output back to STD out at the same time.

Determining the Current Thread

  • Instead of passing an argument to determine current thread, we can use:  threading.current_thread().getName()
  • The name of thread can be changed with the name argument: threading.Thread(name=’func_thread’, target=func)
By |2018-12-02T18:36:24+00:00December 2nd, 2018|Categories: Engineering, Python, Tech|Tags: , , , |0 Comments

About the Author:

Pratik Kataria is currently learning Springboot and Hibernate. Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, Wordpress, Angular, Ionic, MongoDB, SQL and Android. Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.