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

Integrating GPS Coordinates with Python: Unlocking Location-based Insights

GPS (Global Positioning System) has revolutionized the way we navigate and interact with the world around us. In this article, we'll explore how to integrate GPS coordinates with Python, enabling us to fetch location data, perform distance calculations, and gain valuable insights from geospatial information. We'll achieve this using the powerful `geopy` library, which provides easy-to-use geolocation capabilities. Understanding the Importance of Geolocation Geolocation, the process of determining a device's physical location on Earth, has numerous applications across various industries. From location-based services in mobile apps to analyzing spatial data for business intelligence, geolocation is a critical aspect of modern data-driven decision-making. Getting Started with `geopy` The first step is to install the `geopy` library, which simplifies geolocation tasks in Python. Open your terminal or command prompt and run the following command: ```bash pip install geopy ``` Wi...

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 Computer Vision: Capturing Faces from Live Stream Video with Python and OpenCV! 🎥👀

In the world of computer vision, harnessing the power of live stream video to detect and capture faces is both fascinating and empowering. As Python enthusiasts, we can dive into this exciting realm using the OpenCV library, which offers robust tools for image and video processing. In this article, we'll explore how to build a face detection application that captures faces from a live stream video and displays them on the top corner of the screen. The Magic of Face Detection with Haar Cascades Face detection is a fundamental task in computer vision, and the Haar cascades algorithm has proven to be remarkably efficient for this purpose. Haar cascades are a machine learning-based object detection method, which can efficiently detect faces by analyzing patterns of intensity in an image. Getting Started: Setting Up OpenCV and numpy Before we embark on our journey, we need to ensure that we have the OpenCV and numpy libraries installed. You can install them using `pip`: ```bash pip inst...