Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (83 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

Threading In Python: Learn How To Work With Threads In Python

Published on Sep 24,2019 3.1K Views

48 / 62 Blog from Python Fundamentals

Today, Python is one of the most loved programming languages across the world. Since its inception in the 1990s, it has garnered a huge following and enthusiasts and coders who work everyday to make this programming language better. Among the many features that come in-built in the Python ecosystem, one which stands out the most is Threading. Therefore in this article, we will talk all about Threading in Python, how you can make use of it along with its advantages and disadvantages.

Following pointers will be covered in this article,

Let us get started

Threading In Python

What is a Thread in Python?

A thread in Python can simply be defined as a separate flow of execution. What this simply means that in your program, two different processes will be executed in the same time. One interesting aspect of threading in Python is the fact that, after version 3 multiple threads in Python are not executed at the same time, but they just merely appear to. 

While it is an amazing feeling to be running two different processes at the same time, one needs to understand that the current version of Python 3 and above is coded in such a way, that only process can be run at any given point in time. If you however need to two or more processes together at the same time in CPython, you need to code some of your code in other languages as well, such as C, C++ and Java, and then run them through multi threading in Python. 

One of the most well known advantages of threading in Python is its ability to provide a gain in design clarity. 

Before that we have some idea about Threading in Python, let us understand how to start a thread,

Starting a Thread in Python

Now that you are accustomed to the definition of a thread in Python, let us take a look at an example on how you can create your own thread in Python. In order to create a thread in Python, you first need to import the thread library and then instruct it to start() as shown in the example below:

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

Output

Output - Threading In Python - Edureka

When run a thread in Python, you pass it on as a function which contains a list of arguments it needs to execute. In the example shared above, you are instructing Python to run the thread,  thread_function() and pass it to 1 as an argument. 

When you run the above program, the output will look something like this. 

Next bit of this article on ‘Threading in Python’ let us see what daemon threads are,

What are Daemon Threads?

In technical terminology, the daemon can be defined as a process that primarily runs in the background. However, in Python, a daemon thread has a very specific meaning. In Python a daemon thread will shutdown the moment the program exited, although in other programming languages it will continue running in the background. If in a certain program, a thread is not programmed as being a daemon thread, then the interpreter will wait for it to finish its operation and then only shutdown the interpreter. 

To understand this concept better take a look at the example above. In the second last line, the program waits for a few seconds after it has finished all its tasks. This is because it is waiting for the non-daemonic thread to finish its operation and then exit the interface. Once the thread finishes its operation, then only does the program exit. 

Now let us modify the above program and see what happens, if we insert a daemon thread in the code. 

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

When you run the above program with the modifications made, it will look something like this. 

Output - Threading In Python - EdurekaThe difference between these two outputs is that the final line is missing from the latest one. The thread_function() did not get a chance to complete, because we inserted a daemon thread and as it soon it reached the end, it exited the program.

Joining a Thread

Now that you have learned about the concept of creating a thread in Python, along with the concept of a daemonic thread, let us discover how you can join threads in Python. 

By using the join() function in Python you can join two different threads, and also instruct one to wait for the other till it finishes its execution. This feature will often come in handy when you are coding big applications and you need all the processes to be executed in a particular order 

The final bit of this article on ‘Threading in Python’ will show you the working Multiple Threads,

Working with Multiple Threads

In the above examples we have spoken about how you can work with two threads at once. But what if in a certain situation, you need to work with multiple threads at the same time. For better understanding of the situation, take a look at the example below. 

import logging
import threading
import time
def thread_function(name):
logging.info("Thread %s: starting", name)
time.sleep(2)
logging.info("Thread %s: finishing", name)
if __name__ == "__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)
x = threading.Thread(target=thread_function, args=(index,))
threads.append(x)
x.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

Output - Threading In Python - Edureka

In the above program we have followed the same procedure of importing the thread library, starting the thread, creating multiple threads and then use the join() function to combine all together and be executed in a particular order. 

When you run the above program, the result will look something like this. 

Conclusion

It is one of the most handy features of Python. By using it in the correct way, you can make your entire coding process much more easier and efficient. From the above article we hope that you have learned the basics of threading and will continue using it in your day to day programming.

So this is it guys I hope you liked this article.

To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of  this article and we will get back to you.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 23rd March,2024

23rd March

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 20th April,2024

20th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Threading In Python: Learn How To Work With Threads In Python

edureka.co