Introduction
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
Post a Comment