In this blog, I’ll show you how to use multithreading in Python to run two functions in parallel. Multithreading improves program performance by allowing multiple tasks to run simultaneously. It creates two separate threads, each executing a function, and shows how to coordinate the execution of these threads to work together effectively.
Step 1: Import Required Libraries
To get started, we need to import the required modules. The Python standard library contains a module called threading
that provides the functionality you need to work with threads. It also uses the time
module to introduce delays between executions of each function.
Step 2: Define the Functions
To run two functions in parallel, let’s create two functions that print a message every second. This shows how the functions are executed concurrently and how their output is mixed together.
import threading
import time# Define the first function to run in a separate thread
def function_one():
while True:
print("Function One is running.")
time.sleep(1)
# Define the second function to run in a separate thread
def function_two():
while True:
print("Function Two is running.")
time.sleep(1)
Step 3: Create Threads and Start Execution
After defining the functions, we can create two threads to execute them. This can be done using the Python’s threading.Thread
class. Each thread executes the functions assigned to it.
# Create two threads for each function
thread_one = threading.Thread(target=function_one)
thread_two = threading.Thread(target=function_two)
Step 4: Start the Threads
To start the parallel execution, we need to call the start()
method on both threads. Once started, each thread will run independently and at the same time.
# Start both threads
thread_one.start()
thread_two.start()
Step 5: Optional — Wait for Threads to Finish
In this example, the function contains an infinite loop, so the thread runs infinitely. However, if you want to wait until the thread completes before continuing with the main program, you can use the join()
method. In this example, we don’t use join()
because we want the thread to run indefinitely.
# Wait for both threads to finish (this won't happen in this example)
# thread_one.join()
# thread_two.join()
Conclusion:
We’ve seen how to use Python’s multithreading capabilities to run two functions in parallel. Multithreading can improve program performance for I/O-bound tasks, but CPU-bound tasks may require a different approach.