How to create threads in Python – with example

  • Reading time:17 mins read

How to create threads in Python

A thread is a set of operations that are set for execution by a computer. Threading speeds up program execution by allowing us to run parts of a program concurrently.

So threading is a way that we can execute multiple pieces of code at the same time. There are two ways of creating threads in Python and those are; using a class or using a function.

 

 

The thread module is fundamental in thread creation in Python, it provides an interface with functions for starting, stopping and performing various operations on threads.

In this article, we are going to create a thread using a function. However, we will also need to import a few things from the standard library.

 

How to create threads in Python

 

How to create threads in Python – Create a thread

These include the threading module that allows the implementation of a simple locking mechanism for synchronizing threads.

We will also need the time module that will provide us with various functions.

The function below created threads with a waiting time of  3 seconds between each thread.  

 

How to create threads in Python – Run a thread

Using the constructor threading.Thread() we have created a thread that invokes the function run_thread() responsible for creating threads,  as its target.

It is required that the object passed to this constructor should be callable.  Using the start() function we have then started the activity of the thread.

The start() function can only be called once in a thread; this allows us to invoke the run() method of the thread in a separate thread control. A thread cannot start running until the start() function has been invoked.

 

How to create threads in Python

 

In addition, using the sleep() function we have then set the delay time between the creation of each thread to be three seconds. Running the above function results in the output.

How to create threads in Python – Stop a thread

Stopping threads is an important aspect of programming. We need to ensure that threads are not closed abruptly since this may leave a critical resource open.

Critical resources are essential for running systems and this may include a network connection or an important file, to avoid running into issues we must ensure that threads are properly closed.

There are quite a number of ways of killing threads in Python, these include:  

  • Raising an exception.
  • Using an event object.
  • Using a multiprocessing module.
  • Using  _stop() function.
  • Using traces to kill threads.

In this case, we will use a  threading event that will be checked occasionally by the thread.

How to create threads in Python by using the event object

Since we cannot end the thread abruptly we will instead use the event object provided by the threading module that we have imported as the beginning of our program to end the threading cycle using logic.

At the beginning of the program, we have created an event that we have named ‘stop_thread’.

 

stop_thread = threading.Event()

 

An event can exist in two states: set or not set in this case the event is yet to be set since we have just created it. We can always check the status of an event using the function is_set() function.

This function returns True if an event is set and False otherwise. In this program we have set the function inside the for loop to make sure that the thread is able to check the status of the event now and then.

We have the status of the event to True so that the program is able to check out the status and when the status is True we’re going to break out at a more convenient place.

At the bottom of our program, we have added the time.sleep(3) just before setting the event status to True.

 

How to create threads in Python

 

Naturally, this will cause some delay before the program exits; this will ensure that the thread does not exit immediately by delaying the program from setting the flag to True. 

How to create threads in Python – join() method

We have also added the join() method at the bottom to make sure that the main thread waits for the current thread object to exit.

When we run this program after three seconds the set flag will set the event to be True. This is going to trigger a breakpoint in this thread as shown below.

 

 

We can reduce the number of wait seconds before the thread stops to two. In this case, we will get a lower number.

Nevertheless, the function is still able to execute all threads before the breakpoint is triggered, ensuring that the thread does not exit immediately. 

 

Summary

This is how to create threads in Python. If you’d like to see more programming tutorials, check out our Youtube channel, where we have plenty of Python video tutorials in English.

In our Python Programming Tutorials series, you’ll find useful materials which will help you improve your programming skills and speed up the learning process.

Programming tutorials

Would you like to learn how to code, online? Come and try our first 25 lessons for free at the CodeBerry Programming School.

Learn to code and change your career!

100% ONLINE

IDEAL FOR BEGINNERS

SUPPORTIVE COMMUNITY

SELF-PACED LEARNING

Not sure if programming is for you? With CodeBerry you’ll like it.