-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader_writer.py
83 lines (70 loc) · 1.62 KB
/
reader_writer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#! /usr/bin/env python3
import threading
import time
import copy
#signal = release
#wait = acquire
class RWLock:
def __init__(self):
self.__readSwitch = _LightSwitch()
self.__roomEmpty = threading.Lock()
self.__turnstile = threading.Lock()
def reader_acquire(self):
self.__turnstile.acquire()
self.__turnstile.release()
self.__readSwitch.acquire(self.__roomEmpty)
def reader_release(self):
self.__readSwitch.release(self.__roomEmpty)
def writer_acquire(self):
self.__turnstile.acquire()
self.__roomEmpty.acquire()
def writer_release(self):
self.__turnstile.release()
self.__roomEmpty.release()
class _LightSwitch:
def __init__(self):
self.__counter = 0
self.__mutex = threading.Lock()
def acquire(self, lock):
self.__mutex.acquire()
self.__counter += 1
if self.__counter == 1:
lock.acquire()
self.__mutex.release()
def release(self, lock):
self.__mutex.acquire()
self.__counter -= 1
if self.__counter == 0:
lock.release()
self.__mutex.release()
class Reader(threading.Thread):
def run(self):
print (self, 'start')
rwl.reader_acquire()
print (self, 'acquired')
time.sleep(5)
print (self, 'finish')
rwl.reader_release()
class Writer(threading.Thread):
def run(self):
print (self, 'start')
rwl.writer_acquire()
print (self, 'acquired')
time.sleep(15)
print (self, 'finish')
rwl.writer_release()
if __name__ == '__main__' :
rwl = RWLock()
Reader().start()
time.sleep(1)
Reader().start()
time.sleep(1)
Reader().start()
time.sleep(1)
Writer().start()
time.sleep(1)
Reader().start()
time.sleep(1)
Writer().start()
time.sleep(1)
Reader().start()