Python threading – Python multithreading

Filed Under: Python

Python threading module is used to implement multithreading in python programs. In this lesson, we will study about Thread and different functions of python threading module. Python multiprocessing is one of the similar module that we looked into sometime back.

What is a Thread?

In Computer Science, threads are defined as the smallest unit of work which is scheduled to be done by an Operating System.

Some points to consider about Threads are:

  • Threads exists inside a process.
  • Multiple threads can exist in a single process.
  • Threads in same process share the state and memory of the parent process.

This was just a quick overview of Threads in general. This post will mainly focus on the threading module in Python.

Python threading

Let us introduce python threading module with a nice and simple example:


import time
from threading import Thread

def sleepMe(i):
    print("Thread %i going to sleep for 5 seconds." % i)
    time.sleep(5)
    print("Thread %i is awake now." % i)

for i in range(10):
    th = Thread(target=sleepMe, args=(i, ))
    th.start()

When we run this script, the following will be the output:
Python Threading Example, Python multithreading example

When you run this program, the output might be different as parallel threads doesn’t have any defined order of their life.

Python threading functions

We will reuse the last simple program we wrote with threading module and build up the program to show different threading functions.

threading.active_count()

This function returns the number of threads currently in execution. Let us modify the last script’s sleepMe(...) function. Our new script will look like:


import time
import threading
from threading import Thread

def sleepMe(i):
    print("Thread %i going to sleep for 5 seconds." % i)
    time.sleep(5)
    print("Thread %i is awake now." % i)

for i in range(10):
    th = Thread(target=sleepMe, args=(i, ))
    th.start()
    print("Current Thread count: %i." % threading.active_count())

This time, we will have a new output showing how many threads are active. Here is the output:
Python multithreading example, python threading active count

Note that active thread count, after all 10 threads has started is not 10 but 11. This is because it also counts the main thread inside from other 10 threads were spawned.

threading.current_thread()

This function returns the current thread in execution. Using this method, we can perform particular actions with the obtained thread. Let us modify our script to use this method now:


import time
import threading
from threading import Thread

def sleepMe(i):
    print("Thread %s going to sleep for 5 seconds." % threading.current_thread())
    time.sleep(5)
    print("Thread %s is awake now.\n" % threading.current_thread())

#Creating only four threads for now
for i in range(4):
    th = Thread(target=sleepMe, args=(i, ))
    th.start()

The output of the above script will be:
Python Threading Current Thread

threading.main_thread()

This function returns the main thread of this program. More threads can be spawned form this thread. Let us see this script:


import threading
print(threading.main_thread())

Now, let’s run this script:
Python Main Thread

As shown in the image, it is worth noticing that the main_thread() function was only introduced in Python 3. So take care that you use this function only when using Python 3+ versions.

threading.enumerate()

This function returns a list of all active threads. It is easy to use. Let us write a script to put it in use:


import threading
for thread in threading.enumerate():
    print("Thread name is %s." % thread.getName())

Now, let’s run this script:
Python Threading Enumerate

We were having only Main thread when we executed this script, hence the output.

threading.Timer()

This function of threading module is used to create a new Thread and letting it know that it should only start after a specified time. Once it starts, it should call the specified function. Let’s study it with an example:


import threading

def delayed():
    print("I am printed after 5 seconds!")

thread = threading.Timer(3, delayed)
thread.start()

Now, let’s run this script:
Python Threading Timer

Python Multithreading

In this post, we saw some functions in the threading module in Python and how it provides convenient methods to control Threads in a multithreaded environment.

Reference: API Doc

Comments

  1. MVA says:

    Nice article, but I have one doubt. In timer example, your are passing 3 but in string you wrote “I am printed after 5 seconds!”. So I am confused that whether delayed function will be called after 3 secs or 5?

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages