how to implement reader writer problem? using file handeling

Viewed 26

I have to implement the reader writer problem in OS using python, i have created one txt file through code where writer writes the data and readers read the data from that file

Codition to be use is :
At a time multiple readers allowed

At a time multiple writers not allowed

At a time one reader one writer not allowed

I did this code, is this the right implementation please give a feedback or edit if it is necessary.

import threading as thread
import random
from threading import Semaphore
import os

global x                #Shared Data
x = 0
lock = Semaphore(1)    #Lock for synchronising access

def Reader():
    global x
    lock.acquire()      #Acquire the lock before Reading (mutex approach)   
    print('Reader is Reading!')
    x = open("C:\\Users\\varal\\Documents\\readme.txt", "r")
    print(x.read())
    lock.release()      #Release the lock after Reading
    print()

def Writer():
    global x
    lock.acquire()      #Acquire the lock before Writing
    print('Writer is Writing!')
    x = open("C:\\Users\\varal\\Documents\\readme.txt", 'w')  #Write the data on file
    for n in range(0, 2):
        x.write(str(random.randint(0, 10000)))
        x.write(",")
    x.write(str(random.randint(0, 10000)))
    x.close()
    print('Writer is Releasing the lock!')
    lock.release()      #Release the lock after Writing
    print()

if __name__ == '__main__':
    for i in range(0, 10):
        randomNumber = random.randint(0, 100)   #Generate a Random number between 0 to 100
        if(randomNumber > 50):
            Thread1 = thread.Thread(target = Reader)
            Thread1.start()
        else:
            Thread2 = thread.Thread(target = Writer)
            Thread2.start()

Thread1.join()
Thread2.join()
0 Answers
Related