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 – 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.
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.
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
- How to use the Python for loop
- How to use Python Sets
- How to use a Python Dictionary
- How to use Python Classes
- How to use Python Range
- How to use Python if-else statements
- How to use Python RegEx
- How to use Python Lists
- How to use Python Enumerate
- How to use Python Functions
- How to use Python Split
- How to use Python Try-Except
- How to use Python Tuples
- How to use Python Arrays
- How to use Python Sort
- How to use the Python DateTime
- How to download Python?
- How to use the Python FileWrite function
- How to use Python Lambda
- How to use Python ListAppend
- How to use Python ListComprehension
- How to use Python Map
- How to use Python Operators
- How to use Python Pandas
- How to use Python Requests
- How to use Python Strings
- How to use Python Count
- How to use Python Comments
- How to use the Python File Reader method
- How to use the Python IDE-s
- How to use Python logging
- How to use Python Print
- How to use the Python Zip
- How to use Python Append
- How to use Python Global Variables
- How to use the Python join method
- How to use Python list length
- How to use Python JSON files
- How to use Python Modulo
- How to use Python file opening methods
- How to use Python round
- How to use Python sleep
- How to use Python replace
- How to use Python strip
- How to use the Python Time module
- How to use Python unittests
- How to save data to a text file using Context Manager?
- How to use Python external modules
- How to use Python find
- How to install the Python pip package manager
- How to delete files in Python
- Parsing XML files in Python
- How to make a GUI in Python
- How to use Python in Command Prompt
- How to Run a Python Program in VS Code
- How to run a program in Python IDLE
- How to run a program in Jupyter Notebook
- How to read a text file in Python
- How to add numbers in Python
- How to ask for user input in Python
- How to debug in Python
- How to create a thread in Python
- How to import a library in Python
- How to use the PIP package manager
- How to use classes in Python
- How to reverse strings in Python
- How to convert a string to int in Python
- How to print on the same line in Python
- How to remove items from a list
- How to add to a dictionary in Python
- How to raise an exception in Python
- How to throw an exception in Python
- How to stop a program in Python
- How to use Python assert
- How to use the Python compiler
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.
