2 Synchronization primitives:
4 - reader-writer lock (preference to writers)
6 (Contributed to Django by eugene@lazutkin.com)
12 import dummy_threading
as threading
16 Classic implementation of reader-writer lock with preference to writers.
18 Readers can access a resource simultaneously.
19 Writers get an exclusive access.
21 API is self-descriptive:
28 self
.mutex
= threading
.RLock()
29 self
.can_read
= threading
.Semaphore(0)
30 self
.can_write
= threading
.Semaphore(0)
31 self
.active_readers
= 0
32 self
.active_writers
= 0
33 self
.waiting_readers
= 0
34 self
.waiting_writers
= 0
36 def reader_enters(self
):
39 if self
.active_writers
== 0 and self
.waiting_writers
== 0:
40 self
.active_readers
+= 1
41 self
.can_read
.release()
43 self
.waiting_readers
+= 1
46 self
.can_read
.acquire()
48 def reader_leaves(self
):
51 self
.active_readers
-= 1
52 if self
.active_readers
== 0 and self
.waiting_writers
!= 0:
53 self
.active_writers
+= 1
54 self
.waiting_writers
-= 1
55 self
.can_write
.release()
59 def writer_enters(self
):
62 if self
.active_writers
== 0 and self
.waiting_writers
== 0 and self
.active_readers
== 0:
63 self
.active_writers
+= 1
64 self
.can_write
.release()
66 self
.waiting_writers
+= 1
69 self
.can_write
.acquire()
71 def writer_leaves(self
):
74 self
.active_writers
-= 1
75 if self
.waiting_writers
!= 0:
76 self
.active_writers
+= 1
77 self
.waiting_writers
-= 1
78 self
.can_write
.release()
79 elif self
.waiting_readers
!= 0:
80 t
= self
.waiting_readers
81 self
.waiting_readers
= 0
82 self
.active_readers
+= t
84 self
.can_read
.release()