We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

General

Threading in Python

Threading in Python

Threading in Python

Python is considered to be the most preferred programming language by the programmer across the globe due to its user-friendly and straightforward functions. Python achieved many coders, enthusiast, and a huge following who works every day since its commencements in the 1990s to make the programming language better. Threading is one crucial feature that stands unique among other built-in features incorporated in Python eco-systems. In this tutorial, let’s check about threading in Python in a clear way.

What does the thread represent in Python?

A separate execution is defined as a thread in Python. It indicates there will be two various processes executed at the simultaneous time in your program. One interesting fact about threading in Python is that the Python’s after version 3 multiple threads merely appear to execute at the same time, but it’s not happening.

While running two processes at the simultaneous timings, it would be a great feel for the coders, but it would be felt only if the coders understand the Python version 3. One has to code in other programming languages like C, C++, and java to perform more than one process at the same time in CPython. Once the coding is done in other languages, it can be run through multi-threading in Python.

Threading in Python is an ability to provide a profit in design clarity. It is considered as one of the critical advantages of threading in Python. It is imperative to know how to start the thread. Only then we will have detailed knowledge about threading in Python.

How to start the thread?

The following example clearly shows how to start the thread. One must first need to import the thread library and then guides it to start() to create a thread in Python.

Example Program :

import logging
import threading
import time
def thread_function(nam):
logging.info("Thread %s: starting", nam)
time.sleep(2)
logging.info("Thread %s: finishing", nam)
if __nam__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
logging.info("Main    : before creating thread")
a = threading.Thread(target=thread_function, args=(1,))
logging.info("Main    : before running thread")
a.start()
logging.info("Main    : wait for the thread to finish")
# a.join()
logging.info("Main    : all done")

Output :

19:30:16: Main          : before creating thread
19:30:16: Main          : before running thread
19:30:16: Thread 1: starting
19:30:16: Main          : wait for the thread to finish
19:30:16: Main          : all done
19:30:17: Thread 1: finishing

When running a thread in the Python language, you will pass it on the function with arguments lists that needs the execution. In the above example, you instruct the Python to run thread_function(), the thread and then passing 1 as an argument.

What does Daemon Thread represent?

The process which runs in the background is termed as the Daemon thread. A daemon thread will exit when the program is shut down, but it run continually in the background. In some applications, the thread will not be programmed as the daemon thread. The interpreter waits until the operation is completed, and then the interpreter shuts down the operations.

Let me explain the concept clearly with an example. Let’s alter the above program and check out what will be the result. We are going to insert a daemon thread in the above code.

New code: a= threading.Thread(target=thread_function, args=(1,), daemon=True)

Now we are running the program after making the modifications. Let’s check out the result.

Example Program :

import logging
import threading
import time
def thread_function(nam):
logging.info("Thread %s: starting", nam)
time.sleep(2)
logging.info("Thread %s: finishing", nam)
if __nam__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
logging.info("Main : before creating thread")
a = threading.Thread(target=thread_function, args=(1,), daemon=true)
logging.info("Main : before running thread")
a.start()
logging.info("Main : wait for the thread to finish")
# a.join()
logging.info("Main& : all done")

Output :

19:56:16: Main          : before creating thread
19:56:16: Main          : before running thread
19:56:16: Thread 1: starting
19:56:16: Main          : wait for the thread to finish
19:56:16: Main          : all done

The difference between the above output is that you can see the final line missing the last output. The thread_function()is not completed as we have inserted a daemon thread, and therefore when it reaches the end, it will shut down the program.

How to join a thread?

You can make use of the Join() to join two identical threads. It also helps to instruct the one thread to stop for the other until the first one completes its execution. The joining thread feature helps in the case of executing more prominent applications.

How to work with multiple threads?

All the above examples say about working with two different threads at the same time. But in some specific cases, you will be in the situation to work with various threads at the same time. Let’s look for the below example to have a clear understanding.

import logging
import threading
import time
def thread_function(nam):
logging.info("Thread %s: starting", nam)
time.sleep(2)
logging.info("Thread %s: finishing", nam)
if __nam__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO,
datefmt="%H:%M:%S")
threads = list()
for index in range(3):
logging.info("Main    : create and start thread %d.", index)
a = threading.Thread(target=thread_function, args=(index,))
threads.append(a)
a.start()
for index, thread in enumerate(threads):
logging.info("Main    : before joining thread %d.", index)
thread.join()
logging.info("Main    : thread %d done", index)

Output:

20:03:23: Main: create and start thread 0.
20:03:23: Thread 0: starting
20:03:23:Main: create and start thread1.
20:03:23: Thread 1: starting
20:03:23: Main: create and start thread 2.
20:03:23: Thread 2: starting
20:03:24: Main: before joining thread 0.
20:03:24:Thread 0:finishing
20:03:24: Main  : thread 0 done
20:03:24: Main: before joining thread 1.
20:03:24: Main: thread 1 done
20:03:24: Main: before joining thread 2.
20:03:25: Thread2:finishing
20:03:25: Main  :thread 2 done

I hope the above tutorial helped you to know in-depth about the Threading in Python. Do you have any queries on Threading in Python? Ask us in the comment section below.

Related Blogs:

  1. Brief Overview of Python Language
  2. Python Career opportunities
  3. Python Break Continue
  4. Python Control Flow
  5. Python Data Types
  6. Python Dictionary
  7. Python Exception Handling
  8.  Python File
  9. Python Functions
  10. Python Substring
Besant Technologies WhatsApp