File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change 1+ #Author: OMKAR PATHAK
2+ #In this example, we will see how to implement a simple reader Writer program using Python (Mutex)
3+
4+ import threading as thread
5+ import random
6+
7+ global x #Shared Data
8+ x = 0
9+ lock = thread .Lock () #Lock for synchronising access
10+
11+ def Reader ():
12+ global x
13+ print ('Reader is Reading!' )
14+ lock .acquire () #Acquire the lock before Reading (mutex approach)
15+ print ('Shared Data:' , x )
16+ lock .release () #Release the lock after Reading
17+ print ()
18+
19+ def Writer ():
20+ global x
21+ print ('Writer is Writing!' )
22+ lock .acquire () #Acquire the lock before Writing
23+ x += 1 #Write on the shared memory
24+ print ('Writer is Releasing the lock!' )
25+ lock .release () #Release the lock after Writing
26+ print ()
27+
28+ if __name__ == '__main__' :
29+ for i in range (0 , 10 ):
30+ randomNumber = random .randint (0 , 100 ) #Generate a Random number between 0 to 100
31+ if (randomNumber > 50 ):
32+ Thread1 = thread .Thread (target = Reader )
33+ Thread1 .start ()
34+ else :
35+ Thread2 = thread .Thread (target = Writer )
36+ Thread2 .start ()
37+
38+ Thread1 .join ()
39+ Thread2 .join ()
40+
41+ # print(x)
You can’t perform that action at this time.
0 commit comments