File: locking.py

package info (click to toggle)
python-mpd 3.1.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 472 kB
  • sloc: python: 3,148; makefile: 201; sh: 9
file content (56 lines) | stat: -rw-r--r-- 1,294 bytes parent folder | download
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
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...")