/, Python, Tech/Working with Threads in Python

Working with Threads in Python

What is a Thread?

  • A thread is an active flow of control that can be activated in parallel with other threads within the same process.
  • Each thread can execute a set of instructions independently and in parallel with other processes or threads.
  • They share space addressing and then the data structures.
  • A thread is sometimes called a lightweight process.
  • The implementation of a thread is less onerous than that of a real process.
  • However, unlike process, multiple threads may share many resources.

Processes V/S Threads

  • A process can consist of multiple parallel threads.
  • The creation and management of a thread by the operating system is less expensive in terms of CPU’s resources than the creation and management of a process.
  • Threads are used for small tasks, whereas processes are used for more heavyweight tasks.
  • The threads of the same process share the address space and other resources, while processes are independent of each other.

Threads and Python

  • Thread-based parallelism is the standard way of writing parallel programs
  • The python interpreter is not fully thread-safe
  • In order to support multithreaded Python programs, a global lock called the Global Interpreter Lock (GIL) is used.
  • Only one thread can execute the python code at the same time.
  • Python automatically switches to next thread after a short period of time.
  • If multiple threads attempt to access the same data object, it may end up in an inconsistent state.
from threading import Thread

from time import sleep

# To create a thread in Python, you'll want to make your class work as a thread.
# For this, you should subclass your call from the Thread class

class CookBook(Thread):

    def __init__(self):
        self.message = "Hello parallel code!"

    # this method prints only the message
    def print_message(self):

    # the run method prints ten times the message
    def run(self):
        print("Thread firing up")
        x = 0
        while x < 10:
            x += 1
        print("Thread Ended\n")

# start the main process
print("Process started")

hello_py = CookBook()


print("Process Ended")
  • While the main program has ended, the threads continue to run every 2 seconds.
  • This depicts what threads are: a subtask doing something in parent process.
  • A key point is to make sure no thread keeps running in background.
By |2018-12-02T18:27:25+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.