Python Prac8 14
Python Prac8 14
Page 1 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
Description:
Threading:
Threading is a powerful and essential concept in computer programming that allows for
concurrent execution of multiple threads within a single program. Threads are lightweight
processes that share the same memory space and can run independently, enabling various
functionalities and features. Here are some of the key functionality and features of threading:\
Concurrency: Threading provides a way to achieve concurrency in a program. Concurrency
allows multiple tasks to make progress and execute independently, leading to improved
performance in tasks like I/O-bound operations and responsiveness in applications.
Parallelism: While threading allows for concurrency, it's important to note that due to the Global
Interpreter Lock (GIL) in Python, true parallelism in CPU-bound operations is limited. However,
threading can still provide benefits when handling I/O-bound tasks, where threads can run in
parallel and make better use of multi-core processors.
Creation and Management: Threading in Python is made straightforward through the built-in
threading module. This module offers classes and functions for creating, starting, stopping, and
managing threads.
Thread Safety: Threads can access shared resources, and this shared access can lead to race
conditions and data corruption. Threading provides mechanisms like locks, semaphores, and
conditions to ensure thread safety and proper synchronization.
Parallel Task Execution: Threading allows you to break down a larger task into smaller
subtasks and execute them in parallel. This is particularly useful in scenarios where you have a
set of similar tasks to perform concurrently.
Responsive User Interfaces: Threading is often used in graphical user interfaces (GUIs) to
keep the user interface responsive while performing time-consuming operations in the
background. This prevents the UI from freezing and improves the user experience.
Resource Sharing: Threads can share resources and data with each other, making it easier to
pass information between different parts of your program. However, care must be taken to
ensure data integrity through synchronization.
Deadlock Avoidance: Threading provides tools for managing potential deadlocks, a situation
where threads wait indefinitely for each other to release resources. Techniques like timeout-
based locks and deadlock detection are available for deadlock avoidance.
Distributed Computing: Threading can be used to implement distributed computing and
parallel processing. It is often used in scenarios like web scraping, where multiple threads can
fetch data from multiple sources simultaneously.
Page 2 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
Event Handling: Threads can be used to handle events, such as responding to user input or
reacting to changes in data, in a responsive and timely manner.
Load Balancing: Threading can be employed in load balancing scenarios where multiple
threads are used to distribute and process tasks among different resources, such as CPU
cores.
Task Prioritization: Threading allows you to assign priorities to threads, ensuring that critical
tasks are executed before less important ones.
Example:
import threading
def print_numbers():
for i in range(1, 6):
print(f"Number {i}")
def print_letters():
for letter in 'abcde':
print(f"Letter {letter}")
Synchronization:
Synchronization is the process of coordinating the activities of multiple threads to ensure that
they access shared resources or data in a controlled and orderly manner. In a multithreaded
environment, synchronization is essential to prevent issues like data corruption, race conditions,
and deadlocks. Python offers several mechanisms for synchronization, including locks,
semaphores, and condition variables.
Example:
import threading
total = 0
Page 3 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
lock = threading.Lock()
def increment_total():
global total
for _ in range(1000000):
with lock:
total += 1
def decrement_total():
global total
for _ in range(1000000):
with lock:
total -= 1
thread1 = threading.Thread(target=increment_total)
thread2 = threading.Thread(target=decrement_total)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
Multithreading in Python:
Multithreading in Python is the process of running multiple threads within a Python program.
This enables concurrent execution and can significantly improve the performance of certain
types of applications. Python's Global Interpreter Lock (GIL) can limit the true parallelism of
threads, particularly in CPU-bound operations, but it's still beneficial for I/O-bound tasks.
Page 4 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
Conclusion:
The provided code showcases the fundamental principles of threading in Python. A new thread
is created, and the my_thread_function is executed concurrently with the main thread.
Threading allows for parallel execution, enabling the main thread to continue its tasks while the
new thread performs its designated function. Proper synchronization with join() ensures orderly
program termination. This simple example illustrates the power of threading in enhancing
program efficiency and responsiveness by executing tasks concurrently.
Page 5 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
Output:
Page 6 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
Page 7 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
Conclusion:
The provided code demonstrates the use of threading and synchronization to increment a
shared counter safely. Two threads concurrently execute the increment_counter function, each
adding a million to the counter. A lock (counter_lock) is used to ensure exclusive access to the
shared resource, preventing race conditions. This example showcases the importance of
synchronization in multithreaded applications to maintain data integrity. The final counter value
reflects the successful coordination of the threads, emphasizing the power of threading and
synchronization in concurrent programming.
Output:
Page 8 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
Page 9 of 10
Name : Prasad Prabodh Gade FYMCA/A Roll No : 14
insert_thread = threading.Thread(target=insert_into_queue)
retrieve_thread = threading.Thread(target=retrieve_from_queue)
Conclusion:
The provided code demonstrates the use of the queue.PriorityQueue and threading in Python
for concurrent data insertion and retrieval. An insertion thread adds random items with priorities
to the priority queue, while a retrieval thread continuously retrieves and prints items. The code
showcases the importance of synchronization and coordination in a multithreaded environment,
as the insertion and retrieval threads work together. Additionally, the use of the threading.Event
allows for graceful termination of the retrieval thread. This example highlights how Python's
threading and queue modules can be used to manage shared resources and safely handle
concurrent operations.
Output:
Page 10 of 10