forked from Mic92/python-mpd2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
locking.py
54 lines (43 loc) · 1.26 KB
/
locking.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
from threading import Lock, Thread
from random import choice
from mpd import MPDClient
class LockableMPDClient(MPDClient):
def __init__(self):
super(LockableMPDClient, self).__init__()
self._lock = Lock()
def acquire(self):
self._lock.acquire()
def release(self):
self._lock.release()
def __enter__(self):
self.acquire()
def __exit__(self, type, value, traceback):
self.release()
client = LockableMPDClient()
client.connect("localhost", 6600)
# now whenever you need thread-safe access
# use the 'with' statement like this:
with client: # acquire lock
status = client.status()
# if you leave the block, the lock is released
# it is recommend to leave it soon,
# otherwise your other threads will blocked.
# Let's test if it works ....
def fetch_playlist():
for i in range(10):
if choice([0, 1]) == 0:
with client:
song = client.currentsong()
assert isinstance(song, dict)
else:
with client:
playlist = client.playlist()
assert isinstance(playlist, list)
threads = []
for i in range(5):
t = Thread(target=fetch_playlist)
threads.append(t)
t.start()
for t in threads:
t.join()
print("Done...")