Operating system Lab
Operating system Lab
UW-22-AI-BS-052
BS AI 5th Semester
OS
Assignment: 3
Submitted To:
Ma’am Sadia
Design:
The proposed solution implements several strategies to effectively manage access to the shared
database while ensuring fairness, preventing deadlocks, and allowing for efficient reader-writer
synchronization.
1. Fairness:
Writers are given mechanisms to ensure they are not starved by continuously arriving
readers.
A turnstile mechanism is introduced to ensure that readers and writers take turns
accessing the shared database.
2. Deadlock Prevention:
3. Reader-Writer Synchronization:
Multiple readers can read simultaneously, but they must wait if a writer is currently
accessing the database.
4. Priority Management:
Readers have higher priority by default, but the turnstile semaphore ensures fairness
between readers and writers, preventing indefinite delays for writers.
Synchronization Mechanisms:
Semaphores:
resource_access: Controls access to the shared database, allowing either one writer or
multiple readers.
write_queue: Ensures that writers get a fair chance to write without indefinite delays.
turnstile: Prevents writer starvation by queuing readers and writers fairly.
1. Reader:
2. Writer:
Reader Algorithm
If reader_count is 1, acquire the writer_mutex semaphore to prevent writers from accessing the
critical section.
If reader_count is 0, release the writer_mutex semaphore to allow writers to access the critical
section.
Implementation:
import threading
# Shared variables
def ReadData():
def WriteData():
def Reader():
global reader_count
turnstile.acquire()
turnstile.release()
# Lock reader_count
reader_mutex.acquire()
reader_count += 1
if reader_count == 1:
resource_access.acquire()
reader_mutex.release()
ReadData()
# Lock reader_count
reader_mutex.acquire()
reader_count -= 1
if reader_count == 0:
resource_access.release()
reader_mutex.release()
def Writer():
write_queue.acquire()
# Exclusive access to the database
resource_access.acquire()
WriteData()
# Release resource
resource_access.release()
write_queue.release()
def main():
for r in readers:
r.start()
for w in writers:
w.start()
for r in readers:
r.join()
for w in writers:
w.join()
if __name__ == "__main__":
main()
1. Fairness:
The turnstile semaphore ensures that readers and writers access the database in the
order they arrive, preventing starvation of writers.
The write_queue semaphore ensures that writers wait in a fair queue, allowing them to
access the database when it is their turn.
2. Concurrency:
Writers gain exclusive access to the database using the resource_access semaphore.
3. Synchronization:
The reader_mutex ensures that updates to the reader_count variable are atomic,
preventing race conditions.