Skip to content

Commit febbb67

Browse files
committed
Make a little example of how to use this.
1 parent 27ce712 commit febbb67

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

example.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
from threading import Thread
2+
from mux import RWLock
3+
from time import sleep
4+
5+
lock = RWLock()
6+
shared_resource = ""
7+
8+
9+
def do_writes():
10+
global lock
11+
global shared_resource
12+
13+
print("writer thread waiting for write lock")
14+
15+
with lock.write:
16+
print("writer thread received write lock")
17+
18+
for i in range(10):
19+
print(f"writing {i}")
20+
shared_resource += f"{i} "
21+
sleep(1)
22+
23+
print("writer thread will yield write lock")
24+
25+
26+
def do_read(id):
27+
global lock
28+
global shared_resource
29+
30+
print(f"reader thread {id} waiting for read lock")
31+
32+
with lock.read:
33+
print(f"reader thread {id} received read lock")
34+
35+
print(f"reader thread {id} found '{shared_resource}'")
36+
37+
print(f"reader thread {id} will yield read lock")
38+
39+
40+
threads = []
41+
42+
writer_thread = Thread(target=do_writes, daemon=True)
43+
writer_thread.start()
44+
threads.append(writer_thread)
45+
46+
for i in range(5):
47+
reader_thread = Thread(target=do_read, args=[i])
48+
reader_thread.start()
49+
threads.append(reader_thread)
50+
51+
for t in threads:
52+
t.join()

0 commit comments

Comments
 (0)