0% found this document useful (0 votes)
14 views5 pages

Python Multithreading Lab Manual

This lab manual focuses on Object Oriented System Design using Python, specifically on multithreading concepts such as synchronization and inter-thread communication. Students will learn to create and manage threads, implement synchronization techniques, and apply inter-thread communication through practical exercises. The document includes a sample code and various case study exercises for real-world applications, such as banking systems and online ticket booking.

Uploaded by

suman Das
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

Python Multithreading Lab Manual

This lab manual focuses on Object Oriented System Design using Python, specifically on multithreading concepts such as synchronization and inter-thread communication. Students will learn to create and manage threads, implement synchronization techniques, and apply inter-thread communication through practical exercises. The document includes a sample code and various case study exercises for real-world applications, such as banking systems and online ticket booking.

Uploaded by

suman Das
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

रा ीय प्रौद्यो गक सं ान स क्कम

National Institute of Technology Sikkim

Lab Manual: Object Oriented System Design


(CS13204)

Implemented in Python

Course Instructor: Dr. Pankaj Kumar Keserwani

Department of Computer Science and Engineering

October 31, 2025


Lab Manual (Python) CS13104: Object Oriented System Design

Contents

Lab 8: Thread Synchronization and Inter Thread Communication 2

1
Lab Manual (Python) CS13104: Object Oriented System Design

Lab 8: Thread Synchronization and Inter Thread Com-


munication
Objective: To understand how multithreading enhances performance by executing mul-
tiple tasks concurrently and to learn thread synchronization, inter-thread communication,
and thread control techniques.
Expected Outcome: Students will be able to:

• Create and manage multiple threads using Python’s threading module.

• Implement synchronization using locks, events, and semaphores to avoid race con-
ditions.

• Apply inter-thread communication using shared objects and queues.

• Demonstrate thread suspension, resumption, and stopping mechanisms for real-


world control.

Task Description:

Sample Code:
import threading
import time

# Shared resource
balance = 1000
lock = threading .Lock ()

def deposit ( amount ):


global balance
for _ in range (5):
time. sleep (1)
with lock:
balance += amount
print (f" Deposited { amount }, New Balance : { balance }")

def withdraw ( amount ):


global balance
for _ in range (5):
time. sleep (1.5)
with lock:
if balance >= amount :
balance -= amount
print (f" Withdrawn { amount }, Remaining Balance : { balance }")
else:
print (" Insufficient Balance !")

# Create threads
t1 = threading . Thread ( target =deposit , args =(200 ,))
t2 = threading . Thread ( target =withdraw , args =(150 ,))

# Start threads
[Link] ()
[Link] ()

2
Lab Manual (Python) CS13104: Object Oriented System Design

# Wait for both threads to finish


[Link] ()
[Link] ()

print (" Final Balance :", balance )

Objective: This lab focuses on developing concurrent Python applications using


multithreading. Students will learn synchronization, communication, and thread control
concepts, improving system responsiveness and efficiency in real-world use cases.

Case Study Oriented Exercises for Home Assignment


1. Bank Transaction System
At SafeBank, multiple users access their savings account simultaneously. The program
must synchronize balance updates so that no two users withdraw or deposit at the same
time.

2. Railway Ticket Booking


At RailConnect, several agents book seats concurrently. The system should ensure
that two agents cannot book the same seat using thread locks.

3. Sensor Data Logger


At GreenSense Labs, multiple sensors write temperature readings into a shared file.
Synchronization must ensure no overwriting or data corruption.

4. Order Processing System


At QuickMart, one thread receives customer orders while another processes them.
The system should use a thread-safe queue for communication between producer and
consumer threads.

5. Stock Price Monitor


At FinTrack, one thread fetches live stock prices while another logs them into a file.
The data should be passed between threads using a synchronized queue.

6. Inventory Counter
At ShopTrack, several cash counters update the total items sold. The software must
use locks to prevent race conditions during counter updates.

7. Online Exam Portal


At EduTest, multiple students submit answers simultaneously. The server must safely
update the score database using synchronization.

8. Video Streaming Buffer


At StreamX, one thread downloads video chunks while another plays them. Inter-
thread communication ensures smooth playback using buffering queues.

9. News Aggregator
At InfoPulse, multiple fetcher threads gather articles, and one analyzer thread sum-
marizes them. Communication between fetchers and analyzer must use queues.

3
Lab Manual (Python) CS13104: Object Oriented System Design

10. Email Notification System


At MailEase, an event generator thread creates new notification tasks, while worker
threads send them to users. Proper communication ensures every message is processed
once.

11. Smart Home Automation


At HomeSmart, a monitoring thread checks room temperature continuously. Users
should be able to pause and resume this thread from the main console.

12. Music Player


At TuneBeat, the playback thread should pause when the user presses stop and resume
when play is pressed again, simulating thread control.

13. Factory Machine Controller


At AutoMach Industries, a thread simulates a machine cycle. It should stop when an
emergency signal is triggered and resume after inspection.

14. Data Backup Utility


At SafeStore, the backup process runs in a separate thread. The admin should be able
to suspend, resume, or safely stop the thread to manage system resources.

15. Online Shopping Cart Updater


At ShopEase, multiple threads update product availability and prices. Synchronization
must ensure updates occur sequentially to avoid inconsistencies.

Common questions

Powered by AI

In multimedia applications like TuneBeat, smooth pausing and resuming of threads can be achieved through thread control techniques such as event flags or condition variables. When a user presses stop, the playback thread can listen for a pause event, suspending its operation until a resume event is triggered by the play command. This controlled suspension and resumption allow for immediate response to user inputs without causing playback errors or resource leaks .

In QuickMart’s order processing system, implementing a producer-consumer model with synchronized queues enhances efficiency by decoupling the order receiving and processing stages. One thread acts as a producer, receiving and queuing customer orders, while another thread acts as a consumer, processing them. This structure allows for smooth communication and load balancing without the risk of the consumer trying to process an unreceived order, ensuring reliable and efficient processing .

In StreamX, inter-thread communication ensures smooth playback by enabling synchronization between threads that download video chunks and those that render them. Using buffering queues, downloaded chunks can be efficiently passed to the playback thread, maintaining a seamless viewing experience by ensuring that rendering never outpaces downloading, which would otherwise cause buffering delays .

In inventory systems like ShopTrack’s, synchronization mechanisms such as locks prevent race conditions by ensuring that only one cash counter can update the total items sold at any given time. This serialized access prevents concurrent threads from reading and writing the counter simultaneously, which would otherwise result in incorrect updates and inconsistencies in the inventory record .

In InfoPulse, a news aggregator system, efficiency in managing article fetching and summarization is achieved by employing a queue-based inter-thread communication approach. Multiple fetcher threads can concurrently retrieve articles and place them in a synchronized queue that an analyzer thread consumes, summarizing the content. This design ensures that article fetching and summarization are decoupled, optimizing resource use and enhancing throughput without blocking fetcher threads while waiting for the summarization process .

In online exam portals like EduTest, synchronization is critical to safely update the score database when multiple students submit answers simultaneously. Without proper synchronization, concurrent attempts to write scores could lead to data races, resulting in corrupt or inaccurate database entries. By using thread locks or other synchronization mechanisms, the server can serialize database access, ensuring the integrity and accuracy of the stored results .

In railway ticket booking applications, thread synchronization techniques such as thread locks can prevent data corruption. By employing locks, the system ensures that no two agents can book the same seat simultaneously, thereby preventing the situation where two bookings might overwrite or interfere with one another. This serialized access to shared resources, like seat availability, maintains data integrity .

Thread synchronization in a bank transaction system, such as at SafeBank, ensures that balance updates occur safely and without data races when multiple users access their savings accounts at the same time. Using mechanisms like locks, it prevents multiple threads from performing withdrawal or deposit operations concurrently, which could otherwise lead to inconsistent account balances if two threads try to modify the same balance simultaneously .

In smart home automation systems like HomeSmart, challenges in implementing thread suspension and resumption include maintaining state consistency and responsiveness. Solutions involve using thread control methods provided by threading libraries, allowing users to pause and resume monitoring threads without data loss or inconsistency. Proper use of synchronization objects (such as events) ensures that pausing doesn't interrupt critical monitoring tasks and that resumption correctly restores processing states, keeping the system responsive to real-time changes .

In online shopping systems like ShopEase, synchronization ensures sequential updating of product availability and prices by using locks or transaction-based approaches to control thread access to inventory data. This prevents conflicts and errors that could arise from concurrent updates, guaranteeing that each thread safely completes its update transaction before another begins, thus maintaining data consistency and accuracy .

You might also like