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

Use Python Code to send Text message/SMS

Use Python Code to send Text message/SMS     Prerequisites: Before you begin, make sure you have the following in place: 1. Python installed on your system. 2. A Twilio account. You can sign up for free at https://www.twilio.com/try-twilio.   Step 1: Install Twilio First, you need to install the Twilio Python library. Open your terminal or command prompt and run the following command:    pip install twilio  Step 2: Import Twilio and Send SMS Next, you'll import the Twilio library and use it to send an SMS.  python from twilio.rest import Client  # Your Twilio account SID and Auth Token (get these from your Twilio dashboard) account_sid = "your_account_sid" auth_token = "your_auth_token"   # Create a Twilio client client = Client(account_sid, auth_token)  # Your Twilio phone number (this is the number provided by Twilio to send SMS) twilio_phone_number = "+1234567890"   # The recipient's phone number (in inte...

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...

Mastering the Art of Google Search with Python: Unleashing the Power of Automation

Google, the world's most popular search engine, is a treasure trove of information. As Python enthusiasts, we can harness the power of automation to perform Google searches and extract valuable insights. In this article, we'll dive into using Python to conduct Google searches and fetch the top search result with ease. Understanding the Google Search Process Before we begin, it's crucial to grasp the mechanics of a Google search. When we enter a query into the search bar, Google's search algorithms process the request and retrieve relevant web pages. These pages are then ranked based on various factors, and the top results are displayed on the search results page. Introducing the `googlesearch-python` Library To execute Google searches programmatically, we'll use the `googlesearch-python` library. This library provides a simple interface to conduct Google searches and fetch the top search results. Let's install the library first: ```bash pip install googlesearch-...