Skip to main content

Running Functions Concurrently in Python Using Threading

 Introduction

Python is a versatile programming language known for its simplicity and ease of use. One of its powerful features is the ability to run functions concurrently using threads. In this article, we'll explore how to leverage Python's threading module to run functions in parallel and create a simple example to demonstrate this concept.







Understanding Threading

Threading is a technique that enables multiple threads (smaller units of a program) to execute independently and concurrently within a single process. While Python's Global Interpreter Lock (GIL) prevents true parallel execution in threads for CPU-bound tasks, threading can still offer significant performance benefits for I/O-bound operations.


Creating Concurrent Functions


Let's start by creating two functions that will run concurrently using threading:


python

import threading

import time


def lw():

    while True:

        print('a')

        time.sleep(1)


def b():

    while True:

        pass



Here, we've defined two functions, `lw()` and `b()`. The `lw()` function prints the character 'a' repeatedly with a one-second delay between each print. The `b()` function contains an infinite loop to simulate a long-running task.


Running Functions Concurrently


To run these functions concurrently, we'll utilize Python's `threading` module. We'll create two threads, each targeting one of the functions, and then start these threads.


python

thread1 = threading.Thread(target=lw)

thread2 = threading.Thread(target=b)


thread1.start()

thread2.start()



By calling the `start()` method on each thread, we initiate the execution of the corresponding functions in parallel.


Handling User Interruption


Since our `b()` function contains an infinite loop, our program won't terminate normally. To handle this, we'll add a KeyboardInterrupt exception to gracefully stop the program when the user presses Ctrl+C.


python

try:

    while True:

        pass

except KeyboardInterrupt:

    thread1.join()

    thread2.join()

    print("\nProgram stopped")



In this block of code, the `try` block contains an infinite loop to keep the main thread active. When the user interrupts the program using Ctrl+C, the `except` block is executed. Within this block, we use the `join()` method to ensure that both threads complete their execution before the program terminates.


Conclusion


Threading in Python offers a straightforward way to run functions concurrently and can significantly improve performance, especially for I/O-bound tasks. While the Global Interpreter Lock (GIL) limits true parallel execution in threads for CPU-bound tasks, threading can still provide concurrency benefits.


In this article, we've explored the basics of running functions concurrently using Python's threading module. By creating and starting threads for different functions, we've demonstrated how to achieve concurrent execution. Remember that handling infinite loops is crucial to prevent unresponsiveness and ensure that the program can be terminated gracefully.


Threading is just one approach to concurrency in Python. For CPU-bound tasks, the `multiprocessing` module provides an alternative that utilizes separate processes to bypass the GIL's limitations.


Experiment with threading in Python and discover how it can enhance the efficiency of your programs, particularly in scenarios involving I/O-bound operations.


Comments

Popular posts from this blog

Unleashing the Power of Python GUI: Creating a Simple Link Viewer

As a university student with a passion for Python programming, I am constantly exploring new ways to harness the power of this versatile language. One area that has always intrigued me is Graphical User Interfaces (GUIs). GUIs allow us to interact with our programs visually, making them more user-friendly and engaging. In this article, I will guide you through the process of creating a simple link viewer using Python's built-in library, Tkinter. We will unleash the potential of Tkinter to display buttons that can open various links when clicked. So, let's dive into the magic of Python GUIs! Understanding Tkinter: The Magical Library Tkinter is Python's standard GUI library, providing a simple and powerful way to create graphical interfaces. It comes bundled with most Python installations, which makes it easily accessible and an excellent starting point for GUI development. Creating the Link Viewer: Unleash the Buttons Our goal is to create a link viewer that displays button...

Unleashing the Magic of OpenCV 2: A Journey into the Enchanting World of Computer Vision

As the dawn of computer vision unfolds, our fascination with the unseen world becomes a reality through the magical lens of OpenCV version 2. Join me, Anurag Mishra, on an exhilarating journey as we explore the captivating features of this powerful library, unleashing the true potential of computer vision. Peering into the Enchanted Haar Cascade Classifiers In the enchanting realm of OpenCV version 2, Haar cascade classifiers come to life with the brilliance of machine learning. These mystical classifiers possess the ability to detect and unveil objects hidden within images. From detecting faces to discovering smiles, they become our companions in unraveling the mysteries of the visual world. Embracing the Alchemy of Image Filtering and Convolution The alchemy of image filtering and convolution unfolds before us, as we transform ordinary images into artistic masterpieces. Gaussian blur casts its enchanting spell, creating ethereal visions, while median blur dances gracefully, adding a ...